#!/usr/bin/env python3
"""
Example script to generate a PDF via the Influxion API, poll until it's ready,
and download the resulting PDF file.

This script performs the following steps:
1. Get a OAuth2 token (POST /auth/token).
2. Submits a PDF generation job (POST /pdf/generate).
3. Polls the job status (GET /pdf/{job_id}) until completion.
4. Downloads the generated PDF (GET /pdf/{job_id}/download) to a local file.
"""
import os
import re
import time

import httpx

# Configuration
BASE_URL = "https://influxion.nedomkull.com"
TIMEOUT = 10.0  # seconds for HTTP requests
POLL_INTERVAL = 1.0  # seconds between status checks

CLIENT_ID = os.environ.get("INFLUXION_AZURE_CLIENT_ID", "Or set it here")
CLIENT_SECRET = os.environ.get("INFLUXION_AZURE_CLIENT_SECRET", "Or set it here")

PDF_STANDARD = "pdf/ua-1"
SIGN_KEY_ID = "B1B9EA5014C096A99CFA462A00AC24ED40507BCB"


def get_token(client: httpx.Client) -> str:
    data = {
        "client_id": CLIENT_ID,
        "client_secret": CLIENT_SECRET,
        "scope": "api://d88ae758-e67d-492d-bcc6-63f560ee1f04/.default"
    }
    response = client.post("/auth/token", data=data)
    response.raise_for_status()
    return response.json()["access_token"]


def main() -> None:
    client = httpx.Client(base_url=BASE_URL, timeout=TIMEOUT)
    token = get_token(client)
    client.headers.update({"Authorization": f"Bearer {token}"})

    # Define the payload for PDF generation
    payload = {
        "data": {
            "message": "Hello World!",
        },
        "document_id": None,  # None here means "generate an UUID id for me"
        "pdf_standard": PDF_STANDARD,
        "sign_key_id": SIGN_KEY_ID,
        "html_template": {"id": "1"},  # Use the HTML template with id 1, which is the test page
        "css_template": {"id": "1"},   # Use the CSS template with id 1, which accompanies the test page
    }

    # Submit a generate request
    response = client.post("/pdf/generate", json=payload)
    response.raise_for_status()
    job_id = response.json().get("job_id")
    if job_id is None:
        raise RuntimeError(f"No job_id returned: {response.text}")
    print(f"Job created with ID: {job_id}")

    # Poll for job completion
    while True:
        response = client.get(f"/pdf/{job_id}")
        response.raise_for_status()
        data = response.json()
        status = data.get("status")
        print(f"Job status: {status}")
        if status == "Done":
            break
        if status == "Error":
            error = data.get("error")
            raise RuntimeError(f"PDF generation failed: {error}")
        time.sleep(POLL_INTERVAL)

    # Download the resulting PDF
    response = client.get(f"/pdf/{job_id}/download")
    response.raise_for_status()
    content_disp = response.headers.get("Content-Disposition", "")
    match = re.search(r'filename="(.+)"', content_disp)
    if match:
        output_file = match.group(1)
    else:
        output_file = f"{job_id}.pdf"
    with open(output_file, "wb") as f:
        f.write(response.content)
    print(f"PDF downloaded to {output_file}")


if __name__ == "__main__":
    main()