# pyright: strict
"""Deterministic scorer for structured-output extraction failure fixtures (v1.0).

Scores four dimensions separately so high schema validity never masks silent
production defects: schema validity, field correctness, abstention accuracy,
and cost per correct accepted record.

File map:
- Domain types: enums, typed IDs, discriminated union outputs, and scorecards.
- Boundary parsing: strict JSON parsing from external fixture files and dicts.
- Deterministic checks: sign, arithmetic, and exact field verification helpers.
- Public API: load_fixtures, evaluate_case, and score_suite.
"""

from __future__ import annotations

import json
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from enum import Enum
from pathlib import Path
from typing import Literal, NewType, TypeGuard

# === Domain types ===

FixtureId = NewType("FixtureId", str)


class FailureClass(Enum):
    """Closed taxonomy of structured-output failure modes."""

    MISSING_FACT = "missing_fact"
    CONTRADICTORY_VALUES = "contradictory_values"
    EMPTY_INPUT = "empty_input"
    SIGN_OR_CURRENCY_ERROR = "sign_or_currency_error"
    PROMPT_INJECTION = "prompt_injection"
    OUT_OF_SCOPE_ENUM = "out_of_scope_enum"


class OutcomeKind(Enum):
    """Expected high-level decision for an extraction fixture."""

    EXTRACT = "extract"
    ABSTAIN = "abstain"
    NEEDS_REVIEW = "needs_review"


class DocType(Enum):
    """Allowed document types for extracted financial records."""

    INVOICE = "invoice"
    CREDIT_MEMO = "credit_memo"


class CurrencyCode(Enum):
    """Supported ISO-4217 currency codes."""

    USD = "USD"
    CAD = "CAD"
    EUR = "EUR"
    GBP = "GBP"


@dataclass(frozen=True, slots=True)
class InvoiceFields:
    """Validated extracted fields stored in exact integer minor units."""

    vendor_name: str
    doc_type: DocType
    currency: CurrencyCode
    total_cents: int
    line_item_sum_cents: int


@dataclass(frozen=True, slots=True)
class ExtractedInvoice:
    """Discriminated union variant representing an accepted extraction."""

    fields: InvoiceFields
    status: Literal["extracted"] = "extracted"


@dataclass(frozen=True, slots=True)
class AbstainResult:
    """Discriminated union variant when input lacks an extractable record."""

    reason: str
    status: Literal["abstain"] = "abstain"


@dataclass(frozen=True, slots=True)
class NeedsReviewResult:
    """Discriminated union variant when deterministic invariants conflict."""

    reason: str
    status: Literal["needs_review"] = "needs_review"


ModelOutput = ExtractedInvoice | AbstainResult | NeedsReviewResult


@dataclass(frozen=True, slots=True)
class ExtractionFixture:
    """Single immutable test fixture parsed from fixtures.v1.json."""

    fixture_id: FixtureId
    failure_class: FailureClass
    title: str
    document_text: str
    expected_outcome: OutcomeKind
    expected_fields: InvoiceFields | None
    naive_wrong_payload: Mapping[str, object]
    production_impact: str
    deterministic_rule: str


@dataclass(frozen=True, slots=True)
class CaseEvaluation:
    """Per-fixture grading result separating structure from semantics."""

    fixture_id: FixtureId
    schema_valid: bool
    semantically_correct: bool
    false_acceptance: bool
    invariant_violation: str | None


@dataclass(frozen=True, slots=True)
class SuiteReport:
    """Aggregate scorecard for a candidate extraction pipeline."""

    total_cases: int
    schema_valid_count: int
    extract_cases: int
    field_correct_count: int
    non_extract_cases: int
    abstention_correct_count: int
    correct_accepted_count: int
    false_acceptance_count: int
    total_spend_usd: float
    cost_per_correct_record_usd: float | None
    schema_validity_rate: float
    field_correctness_rate: float
    abstention_accuracy: float
    overall_correctness_rate: float
    passes_check: bool


# === Boundary parsing ===


def _is_str_mapping(value: object) -> TypeGuard[Mapping[str, object]]:
    if not isinstance(value, Mapping):
        return False
    # Boundary narrowing: inspect untyped JSON object keys once at entry.
    keys: tuple[object, ...] = tuple(  # pyright: ignore[reportUnknownVariableType]
        value.keys()  # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
    )
    return all(isinstance(key, str) for key in keys)


def _is_object_list(value: object) -> TypeGuard[list[object]]:
    return isinstance(value, list)


def _require_str(mapping: Mapping[str, object], key: str) -> str:
    value = mapping.get(key)
    if not isinstance(value, str) or not value.strip():
        raise ValueError(f"Expected non-empty string for key '{key}'")
    return value


def _require_int(mapping: Mapping[str, object], key: str) -> int:
    value = mapping.get(key)
    if isinstance(value, bool) or not isinstance(value, int):
        raise ValueError(f"Expected integer for key '{key}'")
    return value


def _parse_invoice_fields(payload: Mapping[str, object]) -> InvoiceFields:
    return InvoiceFields(
        vendor_name=_require_str(payload, "vendor_name"),
        doc_type=DocType(_require_str(payload, "doc_type")),
        currency=CurrencyCode(_require_str(payload, "currency")),
        total_cents=_require_int(payload, "total_cents"),
        line_item_sum_cents=_require_int(payload, "line_item_sum_cents"),
    )


def parse_model_output(payload: Mapping[str, object]) -> ModelOutput:
    """Parse an untrusted JSON dict into a typed discriminated union.

    Args:
        payload: Raw dictionary decoded from an LLM structured response.

    Returns:
        A validated ExtractedInvoice, AbstainResult, or NeedsReviewResult.

    Raises:
        ValueError: If status or required fields violate the schema contract.

    Examples:
        >>> out = parse_model_output({"status": "abstain", "reason": "empty"})
        >>> isinstance(out, AbstainResult)
        True
    """
    status = _require_str(payload, "status")
    match status:
        case "extracted":
            return ExtractedInvoice(fields=_parse_invoice_fields(payload))
        case "abstain":
            return AbstainResult(reason=_require_str(payload, "reason"))
        case "needs_review":
            return NeedsReviewResult(reason=_require_str(payload, "reason"))
        case _:
            raise ValueError(f"Unsupported output status: {status}")


def _parse_fixture(raw: Mapping[str, object]) -> ExtractionFixture:
    expected_raw = raw.get("expected_fields")
    expected_fields: InvoiceFields | None = None
    if expected_raw is not None:
        if not _is_str_mapping(expected_raw):
            raise ValueError("expected_fields must be a JSON object or null")
        expected_fields = _parse_invoice_fields(expected_raw)

    naive_raw = raw.get("naive_schema_valid_wrong_output")
    if not _is_str_mapping(naive_raw):
        raise ValueError("naive_schema_valid_wrong_output must be a JSON object")

    return ExtractionFixture(
        fixture_id=FixtureId(_require_str(raw, "id")),
        failure_class=FailureClass(_require_str(raw, "failure_class")),
        title=_require_str(raw, "title"),
        document_text=_require_str(raw, "document_text"),
        expected_outcome=OutcomeKind(_require_str(raw, "expected_outcome")),
        expected_fields=expected_fields,
        naive_wrong_payload=naive_raw,
        production_impact=_require_str(raw, "production_impact"),
        deterministic_rule=_require_str(raw, "deterministic_rule"),
    )


# === Deterministic checks ===


def check_deterministic_invariants(fields: InvoiceFields) -> str | None:
    """Check domain invariants that JSON schemas cannot express cleanly.

    Args:
        fields: Parsed invoice fields from a candidate extraction.

    Returns:
        An error string describing the first broken invariant, or None if valid.

    Examples:
        >>> bad = InvoiceFields("Acme", DocType.INVOICE, CurrencyCode.USD, 5200, 4800)
        >>> check_deterministic_invariants(bad)
        'total_cents (5200) != line_item_sum_cents (4800)'
    """
    if fields.total_cents != fields.line_item_sum_cents:
        return (
            f"total_cents ({fields.total_cents}) != "
            f"line_item_sum_cents ({fields.line_item_sum_cents})"
        )
    if fields.doc_type is DocType.INVOICE and fields.total_cents <= 0:
        return f"invoice must have positive total_cents, got {fields.total_cents}"
    if fields.doc_type is DocType.CREDIT_MEMO and fields.total_cents >= 0:
        return f"credit_memo must have negative total_cents, got {fields.total_cents}"
    return None


def _matches_expected_fields(actual: InvoiceFields, expected: InvoiceFields) -> bool:
    return (
        actual.vendor_name.strip().lower() == expected.vendor_name.strip().lower()
        and actual.doc_type is expected.doc_type
        and actual.currency is expected.currency
        and actual.total_cents == expected.total_cents
        and actual.line_item_sum_cents == expected.line_item_sum_cents
    )


def _evaluate_parsed(fixture: ExtractionFixture, output: ModelOutput) -> CaseEvaluation:
    match output:
        case ExtractedInvoice(fields=fields):
            invariant_err = check_deterministic_invariants(fields)
            if fixture.expected_outcome is not OutcomeKind.EXTRACT:
                return CaseEvaluation(
                    fixture_id=fixture.fixture_id,
                    schema_valid=True,
                    semantically_correct=False,
                    false_acceptance=True,
                    invariant_violation=invariant_err,
                )
            assert fixture.expected_fields is not None
            exact_match = invariant_err is None and _matches_expected_fields(
                fields, fixture.expected_fields
            )
            return CaseEvaluation(
                fixture_id=fixture.fixture_id,
                schema_valid=True,
                semantically_correct=exact_match,
                false_acceptance=not exact_match,
                invariant_violation=invariant_err,
            )
        case AbstainResult():
            correct = fixture.expected_outcome is OutcomeKind.ABSTAIN
            return CaseEvaluation(
                fixture_id=fixture.fixture_id,
                schema_valid=True,
                semantically_correct=correct,
                false_acceptance=False,
                invariant_violation=None,
            )
        case NeedsReviewResult():
            correct = fixture.expected_outcome is OutcomeKind.NEEDS_REVIEW
            return CaseEvaluation(
                fixture_id=fixture.fixture_id,
                schema_valid=True,
                semantically_correct=correct,
                false_acceptance=False,
                invariant_violation=None,
            )


# === Public API ===


def load_fixtures(path: Path) -> tuple[ExtractionFixture, ...]:
    """Load and validate all versioned extraction fixtures from disk.

    Args:
        path: Path to fixtures.v1.json.

    Returns:
        Immutable tuple of validated ExtractionFixture records.

    Raises:
        ValueError: If the JSON root or any fixture violates schema rules.

    Examples:
        >>> fixtures = load_fixtures(Path("fixtures.v1.json"))
        >>> len(fixtures)
        12
    """
    decoded: object = json.loads(path.read_text(encoding="utf-8"))
    if not _is_str_mapping(decoded):
        raise ValueError("Fixture file root must be a JSON object")
    raw_items = decoded.get("fixtures")
    if not _is_object_list(raw_items):
        raise ValueError("Fixture file must contain a 'fixtures' list")
    parsed: list[ExtractionFixture] = []
    for item in raw_items:
        if not _is_str_mapping(item):
            raise ValueError("Each fixture entry must be a JSON object")
        parsed.append(_parse_fixture(item))
    return tuple(parsed)


def evaluate_case(
    fixture: ExtractionFixture,
    raw_output: Mapping[str, object],
) -> CaseEvaluation:
    """Grade one candidate JSON payload against one extraction fixture.

    Args:
        fixture: Expected ground-truth fixture record.
        raw_output: Raw dictionary returned by a candidate pipeline.

    Returns:
        CaseEvaluation separating schema validity from semantic correctness.

    Examples:
        >>> fx = load_fixtures(Path("fixtures.v1.json"))[0]
        >>> res = evaluate_case(fx, fx.naive_wrong_payload)
        >>> (res.schema_valid, res.semantically_correct, res.false_acceptance)
        (True, False, True)
    """
    try:
        parsed = parse_model_output(raw_output)
    except ValueError as exc:
        return CaseEvaluation(
            fixture_id=fixture.fixture_id,
            schema_valid=False,
            semantically_correct=False,
            false_acceptance=False,
            invariant_violation=str(exc),
        )
    return _evaluate_parsed(fixture, parsed)


def score_suite(
    fixtures: Sequence[ExtractionFixture],
    raw_outputs: Sequence[Mapping[str, object]],
    *,
    total_spend_usd: float,
    min_overall_correctness: float = 0.80,
    max_false_acceptances: int = 0,
) -> SuiteReport:
    """Aggregate per-case grades into a CI scorecard.

    Args:
        fixtures: Ordered sequence of ground-truth fixtures.
        raw_outputs: Ordered sequence of raw candidate JSON dicts.
        total_spend_usd: Total cash spend including failed retries and review labor.
        min_overall_correctness: Minimum required fraction of semantically correct cases.
        max_false_acceptances: Maximum tolerated silent wrong extractions.

    Returns:
        Immutable SuiteReport with separate validity, correctness, and cost metrics.

    Raises:
        ValueError: If sequence lengths differ, fixtures are empty, or spend is negative.

    Examples:
        >>> fxs = load_fixtures(Path("fixtures.v1.json"))
        >>> report = score_suite(fxs, [f.naive_wrong_payload for f in fxs], total_spend_usd=1.20)
        >>> (report.schema_validity_rate, report.overall_correctness_rate, report.passes_check)
        (1.0, 0.0, False)
    """
    if len(fixtures) == 0:
        raise ValueError("fixtures must not be empty")
    if len(fixtures) != len(raw_outputs):
        raise ValueError("fixtures and raw_outputs must have identical length")
    if total_spend_usd < 0:
        raise ValueError("total_spend_usd must be non-negative")

    evals = tuple(evaluate_case(fx, out) for fx, out in zip(fixtures, raw_outputs, strict=True))
    extract_pairs = tuple(
        (fx, ev)
        for fx, ev in zip(fixtures, evals, strict=True)
        if fx.expected_outcome is OutcomeKind.EXTRACT
    )
    non_extract_pairs = tuple(
        (fx, ev)
        for fx, ev in zip(fixtures, evals, strict=True)
        if fx.expected_outcome is not OutcomeKind.EXTRACT
    )

    total = len(evals)
    schema_valid = sum(1 for ev in evals if ev.schema_valid)
    field_correct = sum(1 for _, ev in extract_pairs if ev.semantically_correct)
    abstain_correct = sum(1 for _, ev in non_extract_pairs if ev.semantically_correct)
    correct_total = field_correct + abstain_correct
    false_accepts = sum(1 for ev in evals if ev.false_acceptance)

    cost_per_correct = (total_spend_usd / correct_total) if correct_total > 0 else None
    overall_rate = correct_total / total
    passes = overall_rate >= min_overall_correctness and false_accepts <= max_false_acceptances

    return SuiteReport(
        total_cases=total,
        schema_valid_count=schema_valid,
        extract_cases=len(extract_pairs),
        field_correct_count=field_correct,
        non_extract_cases=len(non_extract_pairs),
        abstention_correct_count=abstain_correct,
        correct_accepted_count=correct_total,
        false_acceptance_count=false_accepts,
        total_spend_usd=total_spend_usd,
        cost_per_correct_record_usd=cost_per_correct,
        schema_validity_rate=schema_valid / total,
        field_correctness_rate=(field_correct / len(extract_pairs)) if extract_pairs else 1.0,
        abstention_accuracy=(abstain_correct / len(non_extract_pairs)) if non_extract_pairs else 1.0,
        overall_correctness_rate=overall_rate,
        passes_check=passes,
    )
