from __future__ import annotations

import re
from dataclasses import replace

from rights_filter.domain.records import Evidence, EvidenceSource


class SearchResultPromoter:
    def promote(self, evidence: list[Evidence]) -> list[Evidence]:
        return [self._promote_item(item) for item in evidence]

    def _promote_item(self, item: Evidence) -> Evidence:
        if item.source != EvidenceSource.NAVER_SEARCH:
            return item

        if item.reason == "Naver search returned no results":
            return replace(item, confidence=0.0, data={**item.data, "promoted": False})

        text = " ".join(
            str(item.data.get(key, ""))
            for key in ("title", "description", "query", "result_url")
        ).lower()
        promoted = _has_named_rights_signal(text)
        data = {
            **item.data,
            "promoted": promoted,
            "promotion_reason": (
                "named person/work search evidence" if promoted else "context-only search evidence"
            ),
        }
        return replace(item, confidence=0.8 if promoted else 0.2, data=data)


def _has_named_rights_signal(text: str) -> bool:
    markers = {
        "iu",
        "official",
        "album",
        "cover",
        "character",
        "webtoon",
        "game",
        "broadcast",
        "drama",
        "copyright",
        "celebrity",
    }
    # Match whole words only. Plain `in` matching let short markers like "iu"
    # or "cover" hit inside unrelated words/URLs ("premium", "discover"),
    # falsely promoting context-only results.
    return any(re.search(rf"\b{re.escape(marker)}\b", text) for marker in markers)
