"""Run one ProteinIQ job safely from a script. Python SDK 0.2.0+. MIT licensed.

Every API example imports this module. It quotes by default, submits only with
--submit and --max-credits, saves the request and idempotency key before the
network call, resumes interrupted runs, and downloads outputs with checksums.
"""
from __future__ import annotations

import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import tempfile
from typing import Callable
import uuid

from proteiniq import ProteinIQ
from proteiniq.errors import ProteinIQError


def save_json(path: Path, value: object) -> None:
    with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=path.parent, delete=False) as handle:
        temporary = Path(handle.name)
        json.dump(value, handle, indent=2)
        handle.write("\n")
    try:
        os.replace(temporary, path)
    finally:
        temporary.unlink(missing_ok=True)


def text_input(slot: str, kind: str, format_name: str, content: str, label: str) -> dict:
    """One entry of a request's inputs[], with the file contents inline."""
    if not content.strip():
        raise ValueError(f"The {slot} input is empty.")
    return {"id": slot, "slotId": slot, "kind": kind, "format": format_name,
            "content": content, "label": label, "source": {"type": "text"}}


def file_input(path: Path, slot: str, kind: str, formats: dict[str, str]) -> dict:
    """Read a local file into an input, mapping its extension to an accepted format."""
    format_name = formats.get(path.suffix.lower())
    if format_name is None:
        raise ValueError(f"{path.name}: use one of {', '.join(sorted(formats))}.")
    return text_input(slot, kind, format_name, path.read_text(encoding="utf-8"), path.name)


def check_quote(quote, ceiling: int | None, metered: bool = False) -> None:
    if quote.blocking_errors:
        raise ValueError(f"Quote rejected: {quote.blocking_errors}")
    if quote.billing.get("mode") != "fixed" and not metered:
        raise ValueError("These examples only submit fixed-price jobs; inspect metered billing separately.")
    if ceiling is not None and quote.estimated_credits > ceiling:
        raise ValueError(f"Quote {quote.estimated_credits} exceeds your {ceiling}-credit limit.")


def collect(client: ProteinIQ, state: dict, output: Path, timeout: float) -> dict:
    """Wait for the job, save its structured result and download every file once."""
    job = client.jobs.wait(state["job_id"], timeout=timeout)
    if job.status != "COMPLETED":
        raise RuntimeError(f"Job {job.id}: {job.status}: {job.error}")
    result = client.results.wait(job.id, timeout=120)
    save_json(output / "results.json", result.results)
    manifest_path = output / "files.json"
    manifest = json.loads(manifest_path.read_text()) if manifest_path.exists() else {}
    for index, file in enumerate(result.files, 1):
        if not file.url:
            raise RuntimeError(f"No download URL for output {file.name}; rerun to refresh links.")
        name = re.sub(r"[^a-zA-Z0-9._-]", "_", file.name or "result-file")[:160]
        destination = output / f"{index:02d}-{name}"
        if destination.exists():
            digest = hashlib.sha256(destination.read_bytes()).hexdigest()
            if manifest.get(destination.name, {}).get("sha256") != digest:
                raise RuntimeError(f"Existing file has no matching checksum: {destination}")
        else:
            client.download_url(file.url, destination)
            digest = hashlib.sha256(destination.read_bytes()).hexdigest()
            manifest[destination.name] = {"source_name": file.name, "sha256": digest}
            save_json(manifest_path, manifest)
    print(f"Completed job {job.id}. Files are in {output}")
    return result.results


def output_files(output: Path, pattern: str) -> list[Path]:
    """Downloaded files whose original server name matches a regular expression."""
    manifest = json.loads((output / "files.json").read_text(encoding="utf-8"))
    return [output / local for local, entry in manifest.items()
            if re.search(pattern, entry.get("source_name") or "")]


def run(args: argparse.Namespace, client: ProteinIQ, build_request: Callable[[], dict],
        metered: bool = False) -> dict | None:
    """Quote, then submit at most one job and collect it. Returns the result once complete.

    With metered=True a runtime-billed quote is accepted, and --max-credits is sent
    with the quote and the submission as the spending cap (billing.max_reserved_credits).
    """
    output = args.output
    state_path = output / "request.json"
    workspace_id = client.account.get().workspace.get("id")
    if not workspace_id:
        raise ValueError("Account response did not identify the workspace.")
    if state_path.exists():
        if not args.resume:
            raise ValueError("This output directory already contains a request. Use --resume or a new directory.")
        state = json.loads(state_path.read_text(encoding="utf-8"))
        if state["base_url"] != client.base_url or state["workspace_id"] != workspace_id:
            raise ValueError("Resume with the same ProteinIQ server and workspace as the original request.")
        if state.get("job_id"):
            return collect(client, state, output, args.timeout)
        if not args.submit:
            raise ValueError("Retrying an unconfirmed submission also requires --submit.")
        if state.get("submission"):
            # Resend exactly what the first attempt sent, so the idempotency key
            # returns that job instead of a new quote changing the request.
            return submit_and_collect(client, state, state_path, output, args.timeout)
        request, ceiling = state["request"], state["max_credits"]
    else:
        if args.resume:
            raise ValueError("No saved request to resume.")
        request = build_request()
        ceiling = args.max_credits
        state = {"request": request, "max_credits": ceiling, "idempotency_key": str(uuid.uuid4()),
                 "base_url": client.base_url, "workspace_id": workspace_id}
    spending_cap = {"billing": {"max_reserved_credits": ceiling}} if metered and ceiling and ceiling > 0 else {}
    quote = client.jobs.quote(**request, **spending_cap)
    print(json.dumps(quote.raw, indent=2))
    check_quote(quote, ceiling, metered)
    if not args.submit:
        print("Quote only. No job submitted.")
        return None
    if ceiling is None or ceiling < 1:
        raise ValueError("Submission requires a positive integer --max-credits.")
    state["submission"] = {**request, **(spending_cap if quote.billing.get("mode") != "fixed" else {}),
                           "name": args.job_name, "max_quoted_credits": ceiling}
    return submit_and_collect(client, state, state_path, output, args.timeout)


def submit_and_collect(client: ProteinIQ, state: dict, state_path: Path, output: Path, timeout: float) -> dict:
    # Persist the exact submission and key BEFORE a network call can start a job.
    save_json(state_path, state)
    job = client.jobs.submit(**state["submission"], idempotency_key=state["idempotency_key"])
    state["job_id"] = job.id
    save_json(state_path, state)
    print(f"Job {job.id} submitted. Resume with --output {output} --resume")
    return collect(client, state, output, timeout)


def parser(description: str | None, default_output: str) -> argparse.ArgumentParser:
    """The flags every example shares. Add the example's own inputs to the result."""
    arguments = argparse.ArgumentParser(description=description)
    arguments.add_argument("--output", type=Path, default=Path(default_output))
    arguments.add_argument("--submit", action="store_true", help="Start the job after a successful quote.")
    arguments.add_argument("--max-credits", type=int, help="Highest quote you approve.")
    arguments.add_argument("--resume", action="store_true", help="Continue the request saved in --output.")
    arguments.add_argument("--timeout", type=float, default=3600, help="Seconds to wait locally.")
    arguments.add_argument("--job-name", default="API example")
    return arguments


def main(args: argparse.Namespace, build_request: Callable[[], dict],
         report: Callable[[dict, Path], None], metered: bool = False) -> None:
    """Run the job, then hand the structured result and output folder to report()."""
    args.output.mkdir(parents=True, exist_ok=True)
    # An exclusive lock prevents two local processes overwriting recovery state.
    lock = args.output / ".proteiniq.lock"
    try:
        descriptor = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
    except FileExistsError:
        raise SystemExit(f"{args.output} is in use by another run. Delete {lock} if none is running.")
    try:
        with ProteinIQ() as client:
            result = run(args, client, build_request, metered)
        if result is not None:
            report(result, args.output)
    except (ProteinIQError, ValueError, RuntimeError, TimeoutError) as error:
        raise SystemExit(f"{error}\nKeep this directory and resume the same request. A timeout does not cancel compute.")
    finally:
        os.close(descriptor)
        lock.unlink(missing_ok=True)
