import os
import uuid
import shutil
from flask import Flask, request, jsonify
from pathlib import Path
from process_pdf import process_pdf

UPLOAD_DIR = "uploaded_files"

Path(UPLOAD_DIR).mkdir(parents=True, exist_ok=True)

app = Flask(__name__)

@app.route("/api", methods=["POST"])
def upload_pdf():
    file = request.files.get("file")
    if not file or not file.filename:
        return jsonify({"error": "No file was uploaded"}), 400
    
    if not file.filename.endswith(".pdf"):
        return jsonify({"error": "Only PDF files are allowed"}), 400

    file_path = os.path.join(UPLOAD_DIR, f"{str(uuid.uuid4())}.pdf")
    file.save(file_path)

    data = process_pdf(file_path)

    os.remove(file_path)

    return jsonify(data), 200

@app.route("/", methods=["GET"])
def read_root():
    return jsonify({"message": "Welcome to the Sign Copy Extractor service"})
    
@app.route('/api', methods=['OPTIONS'])
def handle_options():
    response = app.make_default_options_response()
    add_cors_headers(response)
    return response

@app.after_request
def add_cors_headers(response):
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'Content-Type'
    return response


if __name__ == "__main__":
    app.run(debug=True)
