"""Hermes public API client using only the Python standard library."""

from __future__ import annotations

import json
import os
import random
import sys
import time
import uuid
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen

MAX_ATTEMPTS = 4
PER_ATTEMPT_TIMEOUT_SECONDS = 130
TOTAL_TIMEOUT_SECONDS = 300
RETRYABLE_STATUSES = {408, 429, 500, 503}


def retry_delay(headers, attempt: int) -> float:
    retry_after = headers.get("Retry-After", "")
    if retry_after.isdigit():
        return min(30.0, max(1.0, float(retry_after)))
    return min(8.0, 2 ** (attempt - 1)) + random.uniform(0.0, 0.25)


def safe_problem(body: bytes, status: int) -> tuple[str, str]:
    try:
        problem = json.loads(body)
    except (json.JSONDecodeError, UnicodeDecodeError):
        return f"http_{status}", "unknown"
    return str(problem.get("code") or f"http_{status}"), str(problem.get("request_id") or "unknown")


def main() -> int:
    base_url = os.environ["HERMES_API_BASE_URL"].rstrip("/")
    api_key = os.environ["HERMES_API_KEY"]
    message_path = Path(sys.argv[1] if len(sys.argv) > 1 else "synthetic-safe.eml")
    message = message_path.read_bytes()
    idempotency_key = os.environ.get("HERMES_IDEMPOTENCY_KEY", f"sample-{uuid.uuid4()}")
    deadline = time.monotonic() + TOTAL_TIMEOUT_SECONDS

    for attempt in range(1, MAX_ATTEMPTS + 1):
        remaining = deadline - time.monotonic()
        if remaining <= 0:
            print("Hermes client deadline expired", file=sys.stderr)
            return 1
        request = Request(
            f"{base_url}/v1/email-analyses",
            data=message,
            method="POST",
            headers={
                "X-API-Key": api_key,
                "Idempotency-Key": idempotency_key,
                "Content-Type": "message/rfc822",
            },
        )
        try:
            with urlopen(  # noqa: S310 - configured HTTPS endpoint
                request,
                timeout=min(PER_ATTEMPT_TIMEOUT_SECONDS, remaining),
            ) as response:
                result = json.load(response)
            print(result["verdict"], result["risk"], result["completeness"])
            for warning in result["warnings"]:
                print(f"warning: {warning}", file=sys.stderr)
            return 0
        except HTTPError as exc:
            body = exc.read()
            code, request_id = safe_problem(body, exc.code)
            if exc.code not in RETRYABLE_STATUSES or attempt == MAX_ATTEMPTS:
                print(
                    f"Hermes {exc.code}: {code} (request_id={request_id})",
                    file=sys.stderr,
                )
                return 1
            delay = retry_delay(exc.headers, attempt)
        except (URLError, TimeoutError):
            if attempt == MAX_ATTEMPTS:
                print(
                    "Hermes request failed without a terminal response; preserve the "
                    "Idempotency-Key and contact support after bounded retries.",
                    file=sys.stderr,
                )
                return 1
            delay = min(8.0, 2 ** (attempt - 1)) + random.uniform(0.0, 0.25)

        if time.monotonic() + delay >= deadline:
            print("Hermes client deadline expired", file=sys.stderr)
            return 1
        time.sleep(delay)

    return 1


if __name__ == "__main__":
    raise SystemExit(main())
