#!/usr/bin/env python3
"""Upload the invoice or profile example with separate binary image parts."""

import argparse
from contextlib import ExitStack
import json
import mimetypes
import os
from pathlib import Path
import time

import httpx

from generate_markdown_pdf import load_dotenv

HERE = Path(__file__).resolve().parent


def example_payload(example: str) -> tuple[dict, list[Path]]:
    directory = HERE / example
    payload = {
        "data": json.loads((directory / f"{example}-data.json").read_text(encoding="utf-8")),
        "html_template": {"filename": f"{example}.html", "content": (directory / f"{example}.html").read_text(encoding="utf-8")},
        "css_template": {"filename": f"{example}.css", "content": (directory / f"{example}.css").read_text(encoding="utf-8")},
    }
    return payload, sorted(path for path in (directory / "assets").rglob("*") if path.is_file())


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("example", choices=["invoice", "profile"])
    parser.add_argument("--base-url", help="Defaults to INFLUXION_BASE_URL or http://localhost:8000")
    parser.add_argument("--dry-run", action="store_true", help="Validate example files without contacting the API")
    parser.add_argument("-o", "--output", type=Path)
    args = parser.parse_args()
    payload, paths = example_payload(args.example)
    directory = HERE / args.example
    if args.dry_run:
        assert "data:image/" not in payload["html_template"]["content"]
        assert paths, "No example images found"
        print(f"{args.example}: {len(paths)} binary images, {sum(path.stat().st_size for path in paths)} bytes")
        return
    load_dotenv(Path.cwd() / ".env")
    base = args.base_url or os.environ.get("INFLUXION_BASE_URL", "http://localhost:8000")
    form = {"client_id": os.environ["INFLUXION_CLIENT_ID"], "client_secret": os.environ["INFLUXION_CLIENT_SECRET"]}
    if scope := os.environ.get("INFLUXION_SCOPE"):
        form["scope"] = scope
    with httpx.Client(base_url=base, timeout=120) as client, ExitStack() as files:
        response = client.post("/auth/token", data=form)
        response.raise_for_status()
        token = response.json().get("access_token")
        if not token:
            raise SystemExit("Authentication returned no access token")
        client.headers["Authorization"] = f"Bearer {token}"
        assets = [("assets", (path.relative_to(directory).as_posix(), files.enter_context(path.open("rb")),
                               mimetypes.guess_type(path.name)[0] or "application/octet-stream")) for path in paths]
        response = client.post("/pdf/generate/bundle", data={"request": json.dumps(payload)}, files=assets)
        response.raise_for_status()
        job_id = response.json()["job_id"]
        deadline = time.monotonic() + 300
        while True:
            response = client.get(f"/pdf/{job_id}")
            response.raise_for_status()
            status = response.json()
            if status["status"] == "Error":
                raise SystemExit(f"Generation failed: {status.get('error')}")
            if status["status"] == "Done":
                break
            if time.monotonic() > deadline:
                raise SystemExit(f"Timed out waiting for job {job_id}")
            time.sleep(1)
        response = client.get(f"/pdf/{job_id}/download")
        response.raise_for_status()
        output = args.output or Path("output/pdf") / f"{args.example}-bundle.pdf"
        output.parent.mkdir(parents=True, exist_ok=True)
        output.write_bytes(response.content)
        print(output.resolve())


if __name__ == "__main__":
    main()
