from __future__ import annotations

from grantflow.api.public_views import (
    _grounding_trust_summary_payload,
    public_job_metrics_payload,
    public_job_quality_payload,
)

from grantflow.tests.contracts_helpers import fixture_json, sample_quality_contract_job


def test_public_job_quality_payload_matches_golden_snapshot():
    expected = fixture_json("public_job_quality_payload_golden.json")
    job = sample_quality_contract_job()
    inventory_rows = [
        {"doc_family": "donor_policy", "count": 2},
        {"doc_family": "country_context", "count": 0},
        {"doc_family": "responsible_ai_guidance", "count": 1},
    ]
    actual = public_job_quality_payload("job-quality-1", job, ingest_inventory_rows=inventory_rows)
    assert actual == expected


def test_public_job_metrics_payload_core_timing_contract():
    job = sample_quality_contract_job()

    actual = public_job_metrics_payload("job-quality-1", job)

    assert actual["status_change_count"] == 5
    assert actual["pause_count"] == 1
    assert actual["resume_count"] == 1
    assert actual["time_to_first_draft_seconds"] == 60.0
    assert actual["time_to_terminal_seconds"] == 240.0
    assert actual["time_in_pending_hitl_seconds"] == 70.0
    assert actual["grounding_trust_summary"]["trust_score"] == 51.1
    assert actual["grounding_trust_summary"]["trust_level"] == "low"


def test_grounding_trust_summary_is_deterministic():
    citations = [
        {
            "citation_type": "rag_claim_support",
            "citation_confidence": 0.82,
            "traceability_status": "complete",
        },
        {
            "citation_type": "rag_low_confidence",
            "citation_confidence": 0.25,
            "traceability_status": "partial",
        },
        {
            "citation_type": "fallback_namespace",
            "citation_confidence": 0.1,
            "traceability_status": "missing",
        },
    ]

    first = _grounding_trust_summary_payload(citations=citations, grounding_risk_level="low", open_finding_count=1)
    second = _grounding_trust_summary_payload(citations=citations, grounding_risk_level="low", open_finding_count=1)

    assert first == second
    assert first["trust_score"] == 51.1
    assert first["trust_level"] == "low"
    assert first["components"]["confidence_score"] == 0.39
    assert first["components"]["traceability_score"] == 0.5
    assert first["components"]["diagnostic_risk_score"] == 0.2
