from __future__ import annotations

from fastapi.testclient import TestClient

from grantflow.api.app import app
from grantflow.tests.portfolio_quality_helpers import seed_portfolio_quality_jobs

client = TestClient(app)


def test_portfolio_quality_endpoint_aggregates_quality_signals():
    donor = seed_portfolio_quality_jobs()
    response = client.get("/portfolio/quality", params={"donor_id": donor, "status": "done", "hitl_enabled": "true"})
    assert response.status_code == 200
    body = response.json()
    assert body["filters"]["donor_id"] == donor
    assert body["filters"]["status"] == "done"
    assert body["filters"]["hitl_enabled"] is True
    assert body["filters"].get("finding_status") is None
    assert body["filters"].get("finding_severity") is None
    assert body["filters"].get("toc_text_risk_level") is None
    assert body["filters"].get("mel_risk_level") is None
    assert body["warning_level_counts"]["medium"] >= 1
    assert body["warning_level_counts"]["low"] >= 1
    assert body["warning_level_high_job_count"] >= 0
    assert body["warning_level_medium_job_count"] >= 1
    assert body["warning_level_low_job_count"] >= 1
    assert body["warning_level_none_job_count"] >= 0
    assert body["warning_level_high_rate"] is not None
    assert body["warning_level_medium_rate"] is not None
    assert body["warning_level_low_rate"] is not None
    assert body["warning_level_none_rate"] is not None
    assert body["warning_level_job_counts"]["high"] >= 0
    assert body["warning_level_job_counts"]["medium"] >= 1
    assert body["warning_level_job_counts"]["low"] >= 1
    assert body["warning_level_job_counts"]["none"] >= 0
    assert sum(int(v or 0) for v in body["warning_level_job_counts"].values()) == body["job_count"]
    assert body["warning_level_job_rates"]["medium"] is not None
    assert body["warning_level_job_rates"]["low"] is not None
    assert body["grounding_risk_counts"]["high"] >= 1
    assert body["grounding_risk_counts"]["low"] >= 1
    assert body["grounding_risk_job_counts"]["high"] >= 1
    assert body["grounding_risk_job_counts"]["low"] >= 1
    assert sum(int(v or 0) for v in body["grounding_risk_job_counts"].values()) == body["job_count"]
    assert body["grounding_risk_job_rates"]["high"] is not None
    assert body["donor_grounding_risk_counts"]["high"] >= 0
    assert body["donor_grounding_risk_counts"]["medium"] >= 0
    assert body["donor_grounding_risk_counts"]["low"] >= 0
    assert body["donor_grounding_risk_counts"]["unknown"] >= 0
    assert body["high_grounding_risk_donor_count"] >= 0
    assert body["medium_grounding_risk_donor_count"] >= 0
    assert body["job_count"] >= 2
    assert body["avg_quality_score"] is not None
    assert body["avg_critic_score"] is not None
    assert body["severity_weighted_risk_score"] >= 1
    assert body["high_priority_signal_count"] >= 1
    assert body["critic"]["open_findings_total"] >= 1
    assert body["critic"]["high_severity_findings_total"] >= 1
    assert body["critic"]["needs_revision_job_count"] >= 1
    assert body["critic"]["needs_revision_rate"] is not None
    assert "review_readiness_summary" in body
    assert body["review_readiness_summary"]["needs_revision_job_count"] >= 0
    assert body["review_readiness_summary"]["open_critic_findings"] >= 0
    assert body["review_readiness_summary"]["high_severity_open_findings"] >= 0
    assert body["review_readiness_summary"]["open_review_comments"] >= 0
    assert "triage_summary" in body["review_readiness_summary"]
    assert isinstance(body["review_readiness_summary"]["triage_summary"].get("top_reviewer_actions"), list)
    assert body["donor_review_readiness_breakdown"][donor]["job_count"] >= 1
    assert "open_critic_findings_per_job_avg" in body["donor_review_readiness_breakdown"][donor]
    assert "triage_summary" in body["donor_review_readiness_breakdown"][donor]
    assert body["critic"]["llm_finding_label_counts"]["CAUSAL_LINK_DETAIL"] >= 1
    assert body["critic"]["llm_finding_label_counts"]["BASELINE_TARGET_MISSING"] >= 1
    assert body["critic"]["llm_advisory_diagnostics_job_count"] >= 2
    assert body["critic"]["llm_advisory_applied_job_count"] >= 1
    assert body["critic"]["llm_advisory_applied_rate"] is not None
    assert body["critic"]["llm_advisory_candidate_finding_count"] >= 2
    assert body["critic"]["llm_advisory_rejected_reason_counts"]["grounding_threshold_not_met"] >= 1
    assert body["citations"]["citation_count_total"] >= 4
    assert body["citations"]["architect_citation_count_total"] >= 3
    assert body["citations"]["architect_claim_support_citation_count"] >= 1
    assert body["citations"]["architect_claim_support_rate"] is not None
    assert body["citations"]["citation_confidence_avg"] is not None
    assert body["citations"]["citation_type_counts_total"]["rag_claim_support"] >= 1
    assert body["citations"]["citation_type_counts_total"]["fallback_namespace"] >= 1

    assert body["citations"]["architect_citation_type_counts_total"]["rag_claim_support"] >= 1
    assert body["citations"]["mel_citation_type_counts_total"]["fallback_namespace"] >= 1
    assert body["citations"]["low_confidence_citation_count"] >= 1
    assert body["citations"]["architect_rag_low_confidence_citation_count"] >= 1
    assert "mel_rag_low_confidence_citation_count" in body["citations"]
    assert body["citations"]["rag_low_confidence_citation_count"] >= 1
    assert "architect_rag_low_confidence_citation_rate" in body["citations"]
    assert "mel_rag_low_confidence_citation_rate" in body["citations"]
    assert "fallback_namespace_citation_count" in body["citations"]
    assert "fallback_namespace_citation_rate" in body["citations"]
    assert "doc_id_present_citation_count" in body["citations"]
    assert "doc_id_present_citation_rate" in body["citations"]
    assert "retrieval_rank_present_citation_count" in body["citations"]
    assert "retrieval_rank_present_citation_rate" in body["citations"]
    assert "retrieval_confidence_present_citation_count" in body["citations"]
    assert "retrieval_confidence_present_citation_rate" in body["citations"]
    assert "retrieval_metadata_complete_citation_count" in body["citations"]
    assert "retrieval_metadata_complete_citation_rate" in body["citations"]
    assert "architect_doc_id_present_citation_count" in body["citations"]
    assert "architect_doc_id_present_citation_rate" in body["citations"]
    assert "architect_retrieval_rank_present_citation_count" in body["citations"]
    assert "architect_retrieval_rank_present_citation_rate" in body["citations"]
    assert "architect_retrieval_confidence_present_citation_count" in body["citations"]
    assert "architect_retrieval_confidence_present_citation_rate" in body["citations"]
    assert "architect_retrieval_metadata_complete_citation_count" in body["citations"]
    assert "architect_retrieval_metadata_complete_citation_rate" in body["citations"]
    assert "mel_doc_id_present_citation_count" in body["citations"]
    assert "mel_doc_id_present_citation_rate" in body["citations"]
    assert "mel_retrieval_rank_present_citation_count" in body["citations"]
    assert "mel_retrieval_rank_present_citation_rate" in body["citations"]
    assert "mel_retrieval_confidence_present_citation_count" in body["citations"]
    assert "mel_retrieval_confidence_present_citation_rate" in body["citations"]
    assert "mel_retrieval_metadata_complete_citation_count" in body["citations"]
    assert "mel_retrieval_metadata_complete_citation_rate" in body["citations"]
    assert body["citations"]["grounding_risk_level"] in {"high", "medium", "low", "unknown"}
    assert "traceability_gap_citation_count" in body["citations"]
    assert "traceability_gap_citation_rate" in body["citations"]
    assert body["citations"]["architect_threshold_hit_rate_avg"] is not None
    assert body["citations"]["architect_claim_support_rate_avg"] is not None
    assert body["priority_signal_breakdown"]["high_severity_findings_total"]["weight"] >= 1
    assert body["priority_signal_breakdown"]["open_findings_total"]["weighted_score"] >= 1
    assert body["donor_weighted_risk_breakdown"][donor]["weighted_score"] >= 1
    assert body["donor_weighted_risk_breakdown"][donor]["high_priority_signal_count"] >= 1
    assert "architect_rag_low_confidence_citation_count" in body["donor_weighted_risk_breakdown"][donor]
    assert "mel_rag_low_confidence_citation_count" in body["donor_weighted_risk_breakdown"][donor]
    assert "traceability_gap_citation_count" in body["donor_weighted_risk_breakdown"][donor]
    assert "llm_finding_label_counts" in body["donor_weighted_risk_breakdown"][donor]
    assert "mel" in body["donor_weighted_risk_breakdown"][donor]
    assert body["donor_weighted_risk_breakdown"][donor]["mel"]["indicator_job_count"] >= 2
    assert body["donor_weighted_risk_breakdown"][donor]["mel"]["indicator_count_total"] >= 3
    assert body["donor_weighted_risk_breakdown"][donor]["mel"]["risk_level"] in {
        "high",
        "medium",
        "low",
        "unknown",
    }
    assert body["donor_weighted_risk_breakdown"][donor]["mel"]["smart_field_coverage_rate"] is not None
    assert body["donor_weighted_risk_breakdown"][donor]["mel"]["baseline_coverage_rate"] == 0.6667
    assert body["donor_weighted_risk_breakdown"][donor]["mel"]["target_coverage_rate"] == 0.6667
    assert body["donor_weighted_risk_breakdown"][donor]["mel"]["frequency_coverage_rate"] == 1.0
    assert body["donor_weighted_risk_breakdown"][donor]["mel"]["formula_coverage_rate"] == 0.6667
    assert body["donor_weighted_risk_breakdown"][donor]["mel"]["definition_coverage_rate"] == 0.6667
    assert body["donor_weighted_risk_breakdown"][donor]["mel"]["data_source_coverage_rate"] == 1.0
    assert body["donor_weighted_risk_breakdown"][donor]["mel"]["result_level_coverage_rate"] == 1.0
    assert body["donor_weighted_risk_breakdown"][donor]["mel"]["smart_field_coverage_rate"] == 0.8095
    assert body["donor_weighted_risk_breakdown"][donor]["mel"]["baseline_placeholder_count"] >= 1
    assert body["donor_weighted_risk_breakdown"][donor]["mel"]["target_placeholder_count"] >= 1
    assert body["donor_weighted_risk_breakdown"][donor]["mel"]["missing_field_counts"]["baseline"] >= 1
    assert body["donor_weighted_risk_breakdown"][donor]["mel"]["missing_field_counts"]["target"] >= 1
    assert body["donor_weighted_risk_breakdown"][donor]["mel"]["result_level_counts"]["impact"] >= 1
    assert body["donor_weighted_risk_breakdown"][donor]["mel"]["result_level_counts"]["outcome"] >= 1
    assert body["donor_weighted_risk_breakdown"][donor]["mel"]["result_level_counts"]["output"] >= 1
    assert "citation_count_total" in body["donor_weighted_risk_breakdown"][donor]
    assert "architect_citation_count_total" in body["donor_weighted_risk_breakdown"][donor]
    assert "architect_claim_support_citation_count" in body["donor_weighted_risk_breakdown"][donor]
    assert body["donor_weighted_risk_breakdown"][donor]["architect_claim_support_rate"] is not None
    assert "citation_type_counts" in body["donor_weighted_risk_breakdown"][donor]
    assert "architect_citation_type_counts" in body["donor_weighted_risk_breakdown"][donor]
    assert "mel_citation_type_counts" in body["donor_weighted_risk_breakdown"][donor]
    assert "fallback_namespace_citation_rate" in body["donor_weighted_risk_breakdown"][donor]
    assert "doc_id_present_citation_count" in body["donor_weighted_risk_breakdown"][donor]
    assert "doc_id_present_citation_rate" in body["donor_weighted_risk_breakdown"][donor]
    assert "retrieval_rank_present_citation_count" in body["donor_weighted_risk_breakdown"][donor]
    assert "retrieval_rank_present_citation_rate" in body["donor_weighted_risk_breakdown"][donor]
    assert "retrieval_confidence_present_citation_count" in body["donor_weighted_risk_breakdown"][donor]
    assert "retrieval_confidence_present_citation_rate" in body["donor_weighted_risk_breakdown"][donor]
    assert "retrieval_metadata_complete_citation_count" in body["donor_weighted_risk_breakdown"][donor]
    assert "retrieval_metadata_complete_citation_rate" in body["donor_weighted_risk_breakdown"][donor]
    assert body["donor_weighted_risk_breakdown"][donor]["grounding_risk_level"] in {
        "high",
        "medium",
        "low",
        "unknown",
    }
    assert body["donor_weighted_risk_breakdown"][donor]["llm_finding_label_counts"]["CAUSAL_LINK_DETAIL"] >= 1
    assert "llm_advisory_rejected_reason_counts" in body["donor_weighted_risk_breakdown"][donor]
    assert "llm_advisory_applied_label_counts" in body["donor_weighted_risk_breakdown"][donor]
    assert "llm_advisory_rejected_label_counts" in body["donor_weighted_risk_breakdown"][donor]
    assert body["donor_weighted_risk_breakdown"][donor]["llm_advisory_diagnostics_job_count"] >= 2
    assert body["donor_weighted_risk_breakdown"][donor]["llm_advisory_applied_job_count"] >= 1
    assert body["donor_weighted_risk_breakdown"][donor]["llm_advisory_applied_rate"] is not None
    assert body["donor_weighted_risk_breakdown"][donor]["llm_advisory_candidate_finding_count"] >= 2
    assert body["donor_weighted_risk_breakdown"][donor]["llm_advisory_applied_label_counts"]["CAUSAL_LINK_DETAIL"] >= 1
    assert (
        body["donor_weighted_risk_breakdown"][donor]["llm_advisory_rejected_label_counts"]["BASELINE_TARGET_MISSING"]
        >= 1
    )
    assert (
        body["donor_weighted_risk_breakdown"][donor]["llm_advisory_rejected_reason_counts"][
            "grounding_threshold_not_met"
        ]
        >= 1
    )
    assert donor in body["donor_grounding_risk_breakdown"]
    assert body["donor_grounding_risk_breakdown"][donor]["citation_count_total"] >= 1
    assert body["donor_grounding_risk_breakdown"][donor]["architect_citation_count_total"] >= 1
    assert body["donor_grounding_risk_breakdown"][donor]["architect_claim_support_citation_count"] >= 1
    assert body["donor_grounding_risk_breakdown"][donor]["architect_claim_support_rate"] is not None
    assert body["donor_grounding_risk_breakdown"][donor]["fallback_namespace_citation_count"] >= 0
    assert "doc_id_present_citation_count" in body["donor_grounding_risk_breakdown"][donor]
    assert "doc_id_present_citation_rate" in body["donor_grounding_risk_breakdown"][donor]
    assert "retrieval_rank_present_citation_count" in body["donor_grounding_risk_breakdown"][donor]
    assert "retrieval_rank_present_citation_rate" in body["donor_grounding_risk_breakdown"][donor]
    assert "retrieval_confidence_present_citation_count" in body["donor_grounding_risk_breakdown"][donor]
    assert "retrieval_confidence_present_citation_rate" in body["donor_grounding_risk_breakdown"][donor]
    assert "retrieval_metadata_complete_citation_count" in body["donor_grounding_risk_breakdown"][donor]
    assert "retrieval_metadata_complete_citation_rate" in body["donor_grounding_risk_breakdown"][donor]
    if body["donor_grounding_risk_breakdown"][donor]["citation_count_total"] > 0:
        assert body["donor_grounding_risk_breakdown"][donor]["fallback_namespace_citation_rate"] is not None
    assert body["donor_grounding_risk_breakdown"][donor]["grounding_risk_level"] in {
        "high",
        "medium",
        "low",
        "unknown",
    }
    assert body["donor_needs_revision_counts"][donor] >= 1
    assert body["donor_open_findings_counts"][donor] >= 1
    assert body["finding_status_counts"]["open"] >= 1
    assert body["finding_status_counts"]["acknowledged"] >= 0
    assert body["finding_status_counts"]["resolved"] >= 0
    assert body["finding_severity_counts"]["high"] >= 1
    assert body["finding_severity_counts"]["medium"] >= 1
    assert body["finding_severity_counts"]["low"] >= 0
    assert "toc_text_quality" in body
    assert body["toc_text_quality"]["issues_total"] >= 0
    assert body["toc_text_quality"]["placeholder_finding_count"] >= 0
    assert body["toc_text_quality"]["repetition_finding_count"] >= 0
    assert sum(int(v or 0) for v in body["toc_text_quality"]["risk_counts"].values()) == body["job_count"]
    assert body["toc_text_quality"]["high_risk_job_count"] == int(body["toc_text_quality"]["risk_counts"]["high"])
    assert body["toc_text_quality"]["medium_risk_job_count"] == int(body["toc_text_quality"]["risk_counts"]["medium"])
    assert body["toc_text_quality"]["low_risk_job_count"] == int(body["toc_text_quality"]["risk_counts"]["low"])
    assert body["toc_text_quality"]["unknown_risk_job_count"] == int(body["toc_text_quality"]["risk_counts"]["unknown"])
    assert "high_risk_job_rate" in body["toc_text_quality"]
    assert "placeholder_check_status_counts" in body["toc_text_quality"]
    assert "repetition_check_status_counts" in body["toc_text_quality"]
    assert body["toc_text_quality"]["placeholder_check_status_counts"]["unknown"] >= 0
    assert body["toc_text_quality"]["repetition_check_status_counts"]["unknown"] >= 0
    assert body["toc_text_quality"]["risk_counts"]["high"] >= 1
    assert "mel" in body
    assert body["mel"]["indicator_job_count"] >= 2
    assert body["mel"]["indicator_count_total"] >= 3
    assert body["mel"]["avg_indicator_count_per_job"] is not None
    assert body["mel"]["baseline_coverage_rate"] == 0.6667
    assert body["mel"]["target_coverage_rate"] == 0.6667
    assert body["mel"]["frequency_coverage_rate"] == 1.0
    assert body["mel"]["formula_coverage_rate"] == 0.6667
    assert body["mel"]["definition_coverage_rate"] == 0.6667
    assert body["mel"]["data_source_coverage_rate"] == 1.0
    assert body["mel"]["disaggregation_coverage_rate"] == 0.6667
    assert body["mel"]["result_level_coverage_rate"] == 1.0
    assert body["mel"]["smart_field_coverage_rate"] == 0.8095
    assert body["mel"]["risk_level"] == "medium"
    assert body["mel"]["baseline_placeholder_count"] >= 1
    assert body["mel"]["target_placeholder_count"] >= 1
    assert body["mel"]["missing_field_counts"]["baseline"] >= 1
    assert body["mel"]["missing_field_counts"]["target"] >= 1
    assert body["mel"]["missing_field_counts"]["formula"] >= 1
    assert body["mel"]["result_level_counts"]["impact"] >= 1
    assert body["mel"]["result_level_counts"]["outcome"] >= 1
    assert body["mel"]["result_level_counts"]["output"] >= 1
    assert sum(int(v or 0) for v in body["mel_risk_job_counts"].values()) == body["job_count"]
    assert body["mel_risk_job_counts"]["medium"] >= 1
    assert body["donor_mel_risk_counts"]["medium"] >= 1
    assert "eu" not in body["donor_counts"]
