#!/usr/bin/env python3
"""
Convert a Markdown file to PDF via the Influxion API.

Usage:
    python generate_markdown_pdf.py notes.md
    python generate_markdown_pdf.py notes.md --css my-style.css -o notes.pdf
    python generate_markdown_pdf.py notes.md --css my-style.css --no-default-css

The CSS file is appended to Influxion's bundled Markdown stylesheet unless
--no-default-css is given. Credentials are read from INFLUXION_CLIENT_ID and
INFLUXION_CLIENT_SECRET (environment or .env), the server from INFLUXION_BASE_URL.
"""
import argparse
import os
import time
from pathlib import Path

import httpx

DEFAULT_BASE_URL = "http://localhost:8000"
POLL_INTERVAL = 1.0  # seconds between status checks


def load_dotenv(path: Path) -> None:
    if not path.is_file():
        return
    for line in path.read_text(encoding="utf-8").splitlines():
        line = line.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        key, value = line.split("=", 1)
        os.environ.setdefault(key.strip(), value.strip().strip('"').strip("'"))


def main() -> None:
    parser = argparse.ArgumentParser(description="Convert Markdown to PDF with Influxion.")
    parser.add_argument("markdown", type=Path, help="Markdown file to convert")
    parser.add_argument("--css", type=Path, help="Custom CSS file")
    parser.add_argument("--no-default-css", action="store_true", help="Do not include the bundled stylesheet")
    parser.add_argument("--title", help="Document title (default: first H1)")
    parser.add_argument("--lang", default="en", help="Document language code (default: en)")
    parser.add_argument("--pdf-standard", help="e.g. pdf/a-1b or pdf/ua-1")
    parser.add_argument("--sign-key-id", help="Key Vault certificate id for signing")
    parser.add_argument("-o", "--output", type=Path, help="Output file (default: <markdown name>.pdf)")
    args = parser.parse_args()

    load_dotenv(Path.cwd() / ".env")
    base_url = os.environ.get("INFLUXION_BASE_URL", DEFAULT_BASE_URL)
    output = args.output or args.markdown.with_suffix(".pdf")

    payload = {
        "input_type": "markdown",
        "markdown_template": {"filename": args.markdown.name, "content": args.markdown.read_text(encoding="utf-8")},
        "include_default_css": not args.no_default_css,
        "title": args.title,
        "language": args.lang,
        "pdf_standard": args.pdf_standard,
        "sign_key_id": args.sign_key_id,
    }
    if args.css:
        payload["css_template"] = {"filename": args.css.name, "content": args.css.read_text(encoding="utf-8")}

    token_form = {
        "client_id": os.environ["INFLUXION_CLIENT_ID"],
        "client_secret": os.environ["INFLUXION_CLIENT_SECRET"],
    }
    if scope := os.environ.get("INFLUXION_SCOPE"):
        token_form["scope"] = scope

    with httpx.Client(base_url=base_url, timeout=120) as client:
        response = client.post("/auth/token", data=token_form)
        response.raise_for_status()
        client.headers["Authorization"] = f"Bearer {response.json()['access_token']}"

        response = client.post("/pdf/generate", json=payload)
        response.raise_for_status()
        job_id = response.json()["job_id"]

        while True:
            status = client.get(f"/pdf/{job_id}")
            status.raise_for_status()
            info = status.json()
            if info["status"] == "Done":
                break
            if info["status"] == "Error":
                raise SystemExit(f"PDF generation failed: {info.get('error')}")
            time.sleep(POLL_INTERVAL)

        download = client.get(f"/pdf/{job_id}/download")
        download.raise_for_status()
        output.write_bytes(download.content)
    print(f"Wrote {output}")


if __name__ == "__main__":
    main()
