from rights_filter.analysis.evidence_enrichment import EvidenceEnricher
from rights_filter.analysis.llm_assistance import FakeInternalLlmClient, InternalLlmAssistant
from rights_filter.analysis.risk_scoring import RiskScorer
from rights_filter.analysis.search_query_generation import SearchQueryGenerator
from rights_filter.analysis.search_result_promoter import SearchResultPromoter
from rights_filter.domain.records import AnalysisRun, Evidence, EvidenceSource, InMemoryRightsFilterRepository, ScoreResult
from rights_filter.integrations.naver_search import FakeNaverSearchClient, NaverSearchAdapter
from rights_filter.integrations.search_policy import SearchApiPolicy


def _enricher(policy: SearchApiPolicy | None = None) -> EvidenceEnricher:
    return EvidenceEnricher(
        query_generator=SearchQueryGenerator(),
        naver_adapter=NaverSearchAdapter(
            FakeNaverSearchClient(
                response={
                    "items": [
                        {
                            "title": "IU official album cover",
                            "link": "https://example.test/image.jpg",
                            "thumbnail": "https://example.test/thumb.jpg",
                            "page_url": "https://example.test/page",
                        }
                    ]
                }
            )
        ),
        search_policy=policy
        or SearchApiPolicy(compliance_approved=True, allowed_providers={"naver"}),
        promoter=SearchResultPromoter(),
        llm_assistant=InternalLlmAssistant(
            FakeInternalLlmClient(summary="Evidence cites a named work.")
        ),
        scorer=RiskScorer(),
    )


def test_enrichment_adds_naver_evidence_llm_summary_and_score():
    repo = InMemoryRightsFilterRepository()
    run = AnalysisRun.for_submission("submission-1", "v1")
    run.add_evidence(
        Evidence(
            source=EvidenceSource.WEB_DETECTION,
            reason="Web entity matched IU",
            confidence=0.9,
            data={"entity": "IU", "category": "celebrity"},
        )
    )
    run.score = ScoreResult(score=35, band="medium", reasons=["Web entity matched IU"])
    repo.save_analysis_run(run)

    summary = _enricher().enrich_latest(repo, "submission-1")

    latest = repo.analysis_runs_for_submission("submission-1")[-1]
    assert summary.generated_queries == 3
    assert summary.executed_searches == 3
    assert any(item.source == EvidenceSource.NAVER_SEARCH for item in latest.evidence)
    assert any(item.source == EvidenceSource.LLM_SUMMARY for item in latest.evidence)
    assert latest.score.score >= 35


def test_enrichment_is_idempotent_for_same_query_signature():
    repo = InMemoryRightsFilterRepository()
    run = AnalysisRun.for_submission("submission-1", "v1")
    run.add_evidence(
        Evidence(
            source=EvidenceSource.WEB_DETECTION,
            reason="Web entity matched IU",
            confidence=0.9,
            data={"entity": "IU", "category": "celebrity"},
        )
    )
    repo.save_analysis_run(run)
    enricher = _enricher()

    enricher.enrich_latest(repo, "submission-1")
    enricher.enrich_latest(repo, "submission-1")

    latest = repo.analysis_runs_for_submission("submission-1")[-1]
    search_evidence = [
        item for item in latest.evidence if item.source == EvidenceSource.NAVER_SEARCH
    ]
    assert len(search_evidence) == 3


def test_disabled_naver_records_search_skipped_and_still_summarizes():
    repo = InMemoryRightsFilterRepository()
    run = AnalysisRun.for_submission("submission-1", "v1")
    run.add_evidence(
        Evidence(
            source=EvidenceSource.WEB_DETECTION,
            reason="Web entity matched IU",
            confidence=0.9,
            data={"entity": "IU", "category": "celebrity"},
        )
    )
    repo.save_analysis_run(run)

    _enricher(SearchApiPolicy(disabled=True, compliance_approved=True)).enrich_latest(
        repo, "submission-1"
    )

    latest = repo.analysis_runs_for_submission("submission-1")[-1]
    assert any(item.source == EvidenceSource.SEARCH_SKIPPED for item in latest.evidence)
    assert any(item.source == EvidenceSource.LLM_SUMMARY for item in latest.evidence)


def test_missing_analysis_run_returns_failure_summary():
    summary = _enricher().enrich_latest(InMemoryRightsFilterRepository(), "missing")

    assert summary.failed == 1
    assert "missing analysis run" in summary.failure_reasons[0]


def test_enrichment_skips_llm_when_summary_already_present():
    repo = InMemoryRightsFilterRepository()
    run = AnalysisRun.for_submission("submission-1", "v1")
    run.add_evidence(
        Evidence(
            source=EvidenceSource.WEB_DETECTION,
            reason="Web entity matched IU",
            confidence=0.9,
            data={"entity": "IU", "category": "celebrity"},
        )
    )
    run.add_evidence(
        Evidence(source=EvidenceSource.LLM_SUMMARY, reason="existing summary", confidence=0.0, data={})
    )
    repo.save_analysis_run(run)

    enricher = _enricher()
    calls: list[str] = []
    original = enricher.llm_assistant.summarize

    def counting(submission_id, source_evidence):
        calls.append(submission_id)
        return original(submission_id, source_evidence)

    enricher.llm_assistant.summarize = counting
    enricher.enrich_latest(repo, "submission-1")

    # summarize must not run when a summary already exists (result was discarded).
    assert calls == []
