"""SDK resolve() -- submit human review for an escalation."""

from __future__ import annotations

import dataclasses

import httpx

from coalex.config import CoalexConfig

VALID_DECISIONS = {"approved", "rejected", "corrected"}


@dataclasses.dataclass(frozen=True)
class MetricResult:
    """Quality metrics for a single output field."""

    field: str
    metrics: dict[str, float]


@dataclasses.dataclass(frozen=True)
class ResolutionResult:
    """Result of a resolve() call."""

    escalation_id: str
    status: str  # "approved" | "rejected" | "corrected"
    metrics: list[MetricResult]
    resolved_at: str
    resolved_by: str | None = None


def resolve(
    *,
    escalation_id: str,
    decision: str,
    corrections: dict | None = None,
    reviewer: str | None = None,
    reason: str | None = None,
    _config: CoalexConfig | None = None,
    _api_key: str | None = None,
) -> ResolutionResult:
    """Submit human review for an escalation. BYO HITL or Coalex dashboard.

    Args:
        escalation_id: The escalation to resolve.
        decision: One of "approved", "rejected", "corrected".
        corrections: Required when decision="corrected". The corrected output.
        reviewer: Optional reviewer identity.
        reason: Optional human-readable reason.
        _config: Override config (testing only).
        _api_key: Override API key (testing only).
    """
    import coalex as _sdk

    cfg = _config or _sdk._config
    api_key = _api_key or _sdk._api_key
    if cfg is None:
        raise RuntimeError("coalex.register() must be called before resolve()")

    if decision not in VALID_DECISIONS:
        raise ValueError(f"decision must be one of {VALID_DECISIONS}, got '{decision}'")

    if decision == "corrected" and not corrections:
        raise ValueError("corrections required when decision is 'corrected'")

    payload: dict = {"decision": decision}
    if corrections is not None:
        payload["corrections"] = corrections
    if reviewer is not None:
        payload["reviewer"] = reviewer
    if reason is not None:
        payload["reason"] = reason

    with httpx.Client(timeout=30.0) as client:
        resp = client.post(
            f"{cfg.endpoint}/api/v1/escalations/{escalation_id}/resolve",
            json=payload,
            headers={"Authorization": f"Bearer {api_key}"},
        )
        resp.raise_for_status()

    data = resp.json()
    return ResolutionResult(
        escalation_id=data["escalation_id"],
        status=data["status"],
        metrics=[MetricResult(field=m["field"], metrics=m["metrics"]) for m in data.get("metrics", [])],
        resolved_at=data["resolved_at"],
        resolved_by=data.get("resolved_by"),
    )
