from rights_filter.analysis.search_query_generation import SearchQueryGenerator
from rights_filter.domain.records import (
    Evidence,
    EvidenceSource,
    KnowledgeBaseEntry,
    KnowledgeEntryType,
    KnowledgeProvenance,
)


def test_query_generator_plans_web_entities_and_knowledge_aliases_without_duplicates():
    evidence = [
        Evidence(
            source=EvidenceSource.WEB_DETECTION,
            reason="Web entity matched IU",
            confidence=0.9,
            data={"entity": "IU", "category": "celebrity"},
        )
    ]
    knowledge = [
        KnowledgeBaseEntry.create(
            entry_type=KnowledgeEntryType.CELEBRITY,
            name="IU",
            provenance=KnowledgeProvenance.MANUAL,
            aliases=["Lee Ji-eun", "IU"],
            related_keywords=["album cover"],
        )
    ]

    plan = SearchQueryGenerator().plan(evidence, knowledge)

    assert [item.query for item in plan] == [
        "IU 공식 프로필",
        "IU 사진",
        "IU 화보",
        "IU album cover",
        "Lee Ji-eun album cover",
    ]
    assert plan[0].strategy == "google_entity"
    assert plan[0].source == "IU"


def test_query_generator_prioritizes_google_page_titles_and_skips_weak_generic_labels():
    evidence = [
        Evidence(
            source=EvidenceSource.WEB_DETECTION,
            reason="Google page with matching image found",
            confidence=0.9,
            data={"page_title": "Known actor official profile - Example Site", "match": "page"},
        ),
        Evidence(
            source=EvidenceSource.WEB_DETECTION,
            reason="Google weak label gentleman",
            confidence=0.0,
            data={"label": "gentleman", "weak_hint": True},
        ),
    ]

    queries = SearchQueryGenerator().generate(evidence, [])

    assert queries == [
        "Known actor official profile",
        "Known actor official profile image",
    ]


def test_query_generator_uses_weak_label_and_google_page_title_candidates_together():
    evidence = [
        Evidence(
            source=EvidenceSource.WEB_DETECTION,
            reason="Google weak results for IU image",
            confidence=0.0,
            data={
                "page_title": "IU profile - Example Site",
                "label": "IU official profile",
                "weak_hint": True,
            },
        )
    ]

    plan = SearchQueryGenerator().plan(evidence, [])

    assert [item.query for item in plan] == [
        "IU profile",
        "IU profile image",
        "IU official profile",
        "IU official profile image",
    ]
    assert [item.strategy for item in plan] == [
        "google_page",
        "google_page",
        "google_best_guess",
        "google_best_guess",
    ]


def test_query_generator_uses_weak_label_fallback_entity_with_low_priority():
    evidence = [
        Evidence(
            source=EvidenceSource.WEB_DETECTION,
            reason="Google weak entity hint",
            confidence=0.0,
            data={
                "entity": "IU",
                "category": "celebrity",
                "weak_hint": True,
            },
        )
    ]

    plan = SearchQueryGenerator().plan(evidence, [])

    assert [item.query for item in plan] == [
        "IU image",
        "IU",
    ]
    assert [item.strategy for item in plan] == [
        "google_entity",
        "google_entity",
    ]


def test_query_generator_weak_entity_falls_back_when_label_is_generic():
    evidence = [
        Evidence(
            source=EvidenceSource.WEB_DETECTION,
            reason="Google weak hint with generic label",
            confidence=0.0,
            data={
                "entity": "IU",
                "label": "person",
                "weak_hint": True,
            },
        )
    ]

    plan = SearchQueryGenerator().plan(evidence, [])

    assert [item.query for item in plan] == [
        "IU image",
        "IU",
    ]
    assert [item.strategy for item in plan] == [
        "google_entity",
        "google_entity",
    ]


def test_query_generator_uses_specific_google_best_guess_labels_as_low_priority_queries():
    evidence = [
        Evidence(
            source=EvidenceSource.WEB_DETECTION,
            reason="Google weak label IU official profile",
            confidence=0.0,
            data={"label": "IU official profile", "weak_hint": True},
        ),
        Evidence(
            source=EvidenceSource.WEB_DETECTION,
            reason="Google weak label person",
            confidence=0.0,
            data={"label": "person", "weak_hint": True},
        ),
    ]

    plan = SearchQueryGenerator().plan(evidence, [])

    assert [item.query for item in plan] == [
        "IU official profile",
        "IU official profile image",
    ]
    assert all(item.strategy == "google_best_guess" for item in plan)


def test_query_generator_uses_face_crop_page_titles_without_making_them_scoring_evidence():
    evidence = [
        Evidence(
            source=EvidenceSource.WEB_DETECTION,
            reason="Google face crop web evidence",
            confidence=0.75,
            data={
                "page_title": "Known actor official profile - Example Site",
                "face_crop_search": True,
                "weak_hint": True,
            },
        )
    ]

    plan = SearchQueryGenerator().plan(evidence, [])

    assert [item.query for item in plan] == [
        "Known actor official profile",
        "Known actor official profile image",
    ]
    assert all(item.strategy == "google_face_crop_page" for item in plan)


def test_query_generator_limits_query_count_after_priority_sorting():
    evidence = [
        Evidence(
            source=EvidenceSource.WEB_DETECTION,
            reason="Web entity matched IU",
            confidence=0.9,
            data={"entity": "IU", "category": "celebrity"},
        ),
        Evidence(
            source=EvidenceSource.WEB_DETECTION,
            reason="Google page with matching image found",
            confidence=0.9,
            data={"page_title": "IU official profile", "match": "page"},
        ),
    ]

    queries = SearchQueryGenerator().generate(evidence, [], max_queries=3)

    assert queries == [
        "IU official profile",
        "IU official profile image",
        "IU 공식 프로필",
    ]


def test_query_generator_uses_korean_image_suffix_for_korean_page_titles():
    evidence = [
        Evidence(
            source=EvidenceSource.WEB_DETECTION,
            reason="Google page with matching image found",
            confidence=0.9,
            data={"page_title": "김연아 공식 홈페이지 – Example Site", "match": "page"},
        ),
    ]

    queries = SearchQueryGenerator().generate(evidence, [])

    assert queries == [
        "김연아 공식 홈페이지",
        "김연아 공식 홈페이지 이미지",
    ]


def test_query_generator_uses_specific_local_metadata_hints_but_skips_generic_file_names():
    evidence = [
        Evidence(
            source=EvidenceSource.FINGERPRINT,
            reason="Local submission title",
            confidence=0.0,
            data={
                "local_query_hint": True,
                "query": "IU official profile",
                "hint_source": "title",
            },
        ),
        Evidence(
            source=EvidenceSource.FINGERPRINT,
            reason="Local generic file name",
            confidence=0.0,
            data={
                "local_query_hint": True,
                "query": "IMG_1234",
                "hint_source": "file",
            },
        ),
    ]

    plan = SearchQueryGenerator().plan(evidence, [])

    assert [item.query for item in plan] == [
        "IU official profile",
        "IU official profile image",
    ]
    assert all(item.strategy == "local_metadata" for item in plan)
    assert all(item.source == "title" for item in plan)
