from rights_filter.domain.records import (
    AnalysisRun,
    DataClass,
    Evidence,
    EvidenceSource,
    InMemoryRightsFilterRepository,
    KnowledgeBaseEntry,
    KnowledgeEntryType,
    KnowledgeProvenance,
    OperatorDecision,
    ReviewStatus,
    ScoreResult,
)


def test_analysis_run_preserves_evidence_and_latest_score():
    repo = InMemoryRightsFilterRepository()
    run = AnalysisRun.for_submission("submission-1", analysis_version="v1")
    run.add_evidence(
        Evidence(
            source=EvidenceSource.FINGERPRINT,
            reason="Prior rejected image similarity 0.94",
            confidence=0.94,
            data={"similarity": 0.94},
        )
    )
    run.score = ScoreResult(score=91, band="high", reasons=["Prior rejected image similarity 0.94"])

    repo.save_analysis_run(run)

    latest = repo.latest_score_for_submission("submission-1")
    assert latest.score == 91
    assert latest.band == "high"
    assert repo.analysis_runs_for_submission("submission-1")[0].evidence[0].source == EvidenceSource.FINGERPRINT


def test_manual_and_automatic_knowledge_entries_keep_provenance_separate():
    repo = InMemoryRightsFilterRepository()
    manual = KnowledgeBaseEntry.create(
        entry_type=KnowledgeEntryType.CELEBRITY,
        name="아이유",
        provenance=KnowledgeProvenance.MANUAL,
        aliases=["IU", "이지은"],
        policy_memo="권리 증빙 없으면 반려 검토",
        sample_fingerprints=["fp-manual"],
    )
    automatic = KnowledgeBaseEntry.create(
        entry_type=KnowledgeEntryType.REJECTED_IMAGE,
        name="rejected:submission-2",
        provenance=KnowledgeProvenance.AUTOMATIC_REJECTION,
        source_decision_id="decision-2",
        sample_fingerprints=["fp-auto"],
    )

    repo.save_knowledge_entry(manual)
    repo.save_knowledge_entry(automatic)

    assert {entry.provenance for entry in repo.active_knowledge_entries()} == {
        KnowledgeProvenance.MANUAL,
        KnowledgeProvenance.AUTOMATIC_REJECTION,
    }


def test_inactive_knowledge_entry_is_audited_but_excluded_from_matching():
    repo = InMemoryRightsFilterRepository()
    entry = KnowledgeBaseEntry.create(
        entry_type=KnowledgeEntryType.CHARACTER,
        name="테스트 캐릭터",
        provenance=KnowledgeProvenance.MANUAL,
        sample_fingerprints=["fp-character"],
    )
    repo.save_knowledge_entry(entry)

    repo.deactivate_knowledge_entry(entry.id, reason="operator correction")

    assert repo.knowledge_entry(entry.id).active is False
    assert repo.active_knowledge_entries() == []


def test_rejected_decision_creates_linkable_knowledge_source():
    repo = InMemoryRightsFilterRepository()
    decision = OperatorDecision.create(
        submission_id="submission-3",
        status=ReviewStatus.REJECTED,
        memo="유명인 이미지로 판단",
    )
    repo.save_operator_decision(decision)

    entry = repo.create_rejected_image_entry(
        decision_id=decision.id,
        submission_id=decision.submission_id,
        fingerprints=["exact:abc", "phash:def"],
    )

    assert entry.provenance == KnowledgeProvenance.AUTOMATIC_REJECTION
    assert entry.source_decision_id == decision.id
    assert entry.data_classes == {DataClass.IMAGE_FINGERPRINT, DataClass.OPERATOR_NOTE}


def test_search_and_llm_evidence_sources_are_first_class():
    naver = Evidence(
        source=EvidenceSource.NAVER_SEARCH,
        reason="Naver result linked named work",
        confidence=0.82,
        data={
            "query": "IU album cover",
            "rank": 1,
            "result_url": "https://example.test/page",
            "image_url": "https://example.test/image.jpg",
            "thumbnail_url": "https://example.test/thumb.jpg",
            "title": "IU album cover",
            "retrieved_at": "2026-05-25T00:00:00Z",
        },
    )
    summary = Evidence(
        source=EvidenceSource.LLM_SUMMARY,
        reason="Assistant summarized source-linked evidence",
        confidence=0.0,
        data={
            "summary": "Search and web evidence mention the same named work.",
            "source_urls": ["https://example.test/page"],
            "source_evidence_ids": ["evidence-1"],
        },
    )

    assert naver.source == EvidenceSource.NAVER_SEARCH
    assert summary.source == EvidenceSource.LLM_SUMMARY
    assert DataClass.SEARCH_EVIDENCE.value == "search_evidence"
    assert DataClass.LLM_SUMMARY.value == "llm_summary"


def test_repository_can_find_entries_derived_from_source_decision():
    repo = InMemoryRightsFilterRepository()
    entry = repo.create_rejected_image_entry(
        decision_id="decision-1",
        submission_id="submission-1",
        fingerprints=["phash:abc"],
    )

    derived = repo.knowledge_entries_for_source_decision("decision-1")

    assert derived == [entry]
