#!/usr/bin/env python3
"""Python 3.10+, backend only. Standard library; no pip dependencies.

Set INE_API_KEY privately in your server environment, never in browser code.
New job: python3 examples/ine-python.py front.png back.png your-business-id
INE_IDEMPOTENCY_KEY may supply the stable business ID instead of the argument.
Resume GET only: python3 examples/ine-python.py --request-id UUID
Default output omits OCR data. --print-data explicitly prints the whole result.
Uses /api/v3 English field names; names, addresses, and other OCR values are not translated.
"""
import argparse
import json
import os
from pathlib import Path
import re
import sys
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from urllib.error import HTTPError, URLError
from urllib.parse import urlsplit
from urllib.request import HTTPRedirectHandler, Request, build_opener
from uuid import uuid4

UUID_PATTERN = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
MAX_WAIT_SECONDS = 90


class NoRedirects(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None  # Never forward credentials to another host.


def multipart(front, back):
    boundary = "ine-upload-" + uuid4().hex  # Transport boundary, not Idempotency-Key.
    chunks = []
    for field, filename in (("front", front), ("back", back)):
        path = Path(filename)
        if path.stat().st_size > 10 * 1024 * 1024:
            raise ValueError("Each image must be no larger than 10 MiB.")
        data = path.read_bytes()
        mime = "image/png" if data.startswith(b"\x89PNG\r\n\x1a\n") else "image/jpeg" if data.startswith(b"\xff\xd8\xff") else None
        if mime is None:
            raise ValueError("Use PNG or JPG images.")
        chunks.extend([
            (f"--{boundary}\r\nContent-Disposition: form-data; name=\"{field}\"; filename=\"{field}-image\"\r\nContent-Type: {mime}\r\n\r\n").encode("ascii"),
            data, b"\r\n",
        ])
    chunks.append(f"--{boundary}--\r\n".encode("ascii"))
    return b"".join(chunks), f"multipart/form-data; boundary={boundary}"


def retry_delay(value):
    if value and value.isdigit():
        return float(value)
    if value:
        try:
            date = parsedate_to_datetime(value)
            if date.tzinfo is None:
                date = date.replace(tzinfo=timezone.utc)
            return max(0, (date - datetime.now(timezone.utc)).total_seconds())
        except (TypeError, ValueError, OverflowError):
            pass
    return 2.0


def main():
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("front", nargs="?")
    parser.add_argument("back", nargs="?")
    parser.add_argument("idempotency", nargs="?")
    parser.add_argument("--request-id")
    parser.add_argument("--print-data", action="store_true")
    args = parser.parse_args()
    api_key = os.environ.get("INE_API_KEY")
    if not api_key:
        raise ValueError("Set INE_API_KEY in your server environment.")
    origin = os.environ.get("INE_API_URL", "https://ocr.ecostudios.dev").rstrip("/")
    url = urlsplit(origin)
    if not url.hostname or url.username or url.password or url.query or url.fragment or url.path:
        raise ValueError("INE_API_URL must contain only the API origin.")
    if url.scheme != "https" and not (url.scheme == "http" and url.hostname in ("127.0.0.1", "localhost", "::1")):
        raise ValueError("The API key requires HTTPS except for local testing.")
    request_id = args.request_id
    base_headers = {"X-API-Key": api_key, "User-Agent": "ine-api-backend-example/1.0", "Accept": "application/json"}
    headers = dict(base_headers)
    body = None
    method = "GET" if request_id else "POST"
    if request_id:
        if not UUID_PATTERN.fullmatch(request_id) or args.front or args.back or args.idempotency:
            raise ValueError("Use --request-id UUID without image files or an idempotency key.")
    else:
        key = args.idempotency or os.environ.get("INE_IDEMPOTENCY_KEY", "")
        if not args.front or not args.back or not re.fullmatch(r"[A-Za-z0-9._:-]{8,128}", key):
            raise ValueError("Provide front and back images and a stable Idempotency-Key of 8–128 characters.")
        body, headers["Content-Type"] = multipart(args.front, args.back)
        headers["Idempotency-Key"] = key
    route = "/api/v3/ine/" + request_id if request_id else "/api/v3/ine"
    deadline = time.monotonic() + MAX_WAIT_SECONDS
    opener = build_opener(NoRedirects())
    while True:
        try:
            request = Request(origin + route, data=body, headers=headers, method=method)
            try:
                response = opener.open(request, timeout=max(0.1, deadline - time.monotonic()))
            except HTTPError as error:
                response = error  # Read structured API errors without retrying POST.
            with response:
                status = response.status
                response_headers = response.headers
                header_id = response_headers.get("x-request-id", "")
                if UUID_PATTERN.fullmatch(header_id):
                    request_id = header_id
                raw = response.read(128 * 1024 + 1)
                try:
                    result = json.loads(raw) if len(raw) <= 128 * 1024 else None
                except ValueError:
                    result = None
        except (URLError, TimeoutError, OSError, ValueError):
            print(json.dumps({"request_id": request_id, "error": "connection_unconfirmed", "message": "The result could not be confirmed. Keep the same Idempotency-Key and image bytes. Check request_id if available; do not automatically create a new key."}, ensure_ascii=False), file=sys.stderr)
            return 1
        candidate = result.get("request_id") if isinstance(result, dict) else None
        if isinstance(candidate, str) and UUID_PATTERN.fullmatch(candidate):
            request_id = candidate
        if status not in (200, 202) or not isinstance(result, dict):
            structured = result.get("error") if isinstance(result, dict) else None
            if isinstance(structured, dict) and all(isinstance(structured.get(key), str) for key in ("code", "message", "action")):
                error = {key: structured[key] for key in ("code", "message", "action")}
            else:
                error = {"code": "invalid_api_response" if status in (200, 202) else "http_error", "message": "The HTTP response does not match the API format. Keep the same Idempotency-Key and contact support."}
            print(json.dumps({"request_id": request_id, "http_status": status, "error": error, "retry_after": response_headers.get("Retry-After")}, ensure_ascii=False), file=sys.stderr)
            return 1
        if status == 200:
            if result.get("status") != "succeeded":
                raise ValueError("Unexpected response; keep your business transaction identifier.")
            # Your backend can consume result['data']; keep personal data out of logs.
            output = result if args.print_data else {key: result.get(key) for key in ("request_id", "status", "needs_review", "warnings", "expires_at")}
            print(json.dumps(output, ensure_ascii=False, indent=2))
            return 0
        if result.get("status") != "processing" or not isinstance(result.get("request_id"), str) or not UUID_PATTERN.fullmatch(result["request_id"]) or result.get("status_url") != "/api/v3/ine/" + result["request_id"]:
            raise ValueError("Invalid status response. Keep your Idempotency-Key.")
        wait = max(0.25, retry_delay(response_headers.get("Retry-After")))
        if time.monotonic() + wait >= deadline:
            print(json.dumps({key: result[key] for key in ("request_id", "status", "status_url")}, ensure_ascii=False))
            print("The wait ended; check later with --request-id. The POST was not submitted again.", file=sys.stderr)
            return 0
        time.sleep(wait)
        # Build a same-origin GET rather than following a server-supplied URL.
        route, method, body = "/api/v3/ine/" + request_id, "GET", None
        headers = dict(base_headers)


if __name__ == "__main__":
    try:
        sys.exit(main())
    except (ValueError, OSError) as error:
        # Avoid tracebacks containing request objects, file contents or API keys.
        print("An image file could not be read." if isinstance(error, OSError) else str(error), file=sys.stderr)
        sys.exit(1)
