"""
service.py — HTTP service wrapper for qr_merge.

Power Automate calls this service via an HTTP POST action.
The service receives the blank PDF bytes and two URLs, and returns
the completed PDF bytes.

Start locally:
    pip install flask
    python service.py

Deploy to Azure App Service / any WSGI host (gunicorn, etc.):
    gunicorn service:app

---
Power Automate HTTP action config:
    Method: POST
    URI:    http://<your-host>:5000/generate
    Headers:
        Content-Type: application/json
    Body:
        {
          "blank_pdf_base64": "@{base64(outputs('Get_file_content')?['body'])}",
          "submittal_url":    "<https://fileshare.icastinc.com/shared/...Submittal.pdf>",
          "production_url":   "<https://fileshare.icastinc.com/shared/...Shop.pdf>"
        }

Response:
    The completed PDF is returned as raw bytes (Content-Type: application/pdf).
    In Power Automate use "Create file" with body: @{body('HTTP')}
"""

import base64
import os
import sys

from flask import Flask, request, Response, jsonify

try:
    from qr_merge import build_carrier_pdf
except ImportError as e:
    sys.exit(f"Missing dependency: {e}\nRun: pip install flask Pillow qrcode pypdf")

app = Flask(__name__)


@app.post("/generate")
def generate():
    data = request.get_json(force=True, silent=True)
    if not data:
        return jsonify(error="Request body must be JSON"), 400

    blank_b64     = data.get("blank_pdf_base64")
    submittal_url = data.get("submittal_url")
    production_url = data.get("production_url")

    missing = [k for k, v in {
        "blank_pdf_base64": blank_b64,
        "submittal_url":    submittal_url,
        "production_url":   production_url,
    }.items() if not v]
    if missing:
        return jsonify(error=f"Missing fields: {missing}"), 400

    try:
        blank_bytes  = base64.b64decode(blank_b64)
        result_bytes = build_carrier_pdf(blank_bytes, submittal_url, production_url)
    except Exception as exc:
        return jsonify(error=str(exc)), 500

    return jsonify(file_content=base64.b64encode(result_bytes).decode("ascii"))


@app.get("/health")
def health():
    return jsonify(status="ok")


if __name__ == "__main__":
    port = int(os.environ.get("PORT", 5000))
    app.run(host="0.0.0.0", port=port, debug=False)
