"""Submit one document, monitor it, and download verified result artifacts."""

from __future__ import annotations

import argparse
from pathlib import Path

from dcp_client import DCPClient


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("file", type=Path)
    parser.add_argument("--business-id", required=True)
    parser.add_argument("--version", required=True)
    parser.add_argument("--output", type=Path, default=Path("dcp-results"))
    args = parser.parse_args()

    client = DCPClient.from_environment()
    idempotency_key = f"example:{args.business_id}:{args.version}"
    task = client.submit_file(
        args.file,
        idempotency_key,
        external_task_id=args.business_id,
        metadata={"business_id": args.business_id, "version": args.version},
    )
    task_id = str(task.get("id") or task["task_id"])

    def report(progress):
        current = progress.get("current")
        total = progress.get("total")
        pages = (
            f" ({current}/{total})" if current is not None and total is not None else ""
        )
        print(
            f"{progress.get('percent', 0)}% {progress.get('phase', '')}{pages} {progress.get('message', '')}"
        )

    finished = client.wait(task_id, on_progress=report)
    client.raise_for_task(finished)
    for artifact in client.download_result(task_id, args.output):
        print(f"{artifact.artifact_type}: {artifact.path} ({artifact.size} bytes)")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
