from __future__ import annotations

from typing import Any

from rights_filter.domain.records import (
    Evidence,
    EvidenceSource,
    InMemoryRightsFilterRepository,
    ReviewStatus,
)


def detailed_review_for(
    repository: InMemoryRightsFilterRepository,
    submission_id: str,
    image_reference: str | None = None,
) -> dict[str, Any]:
    runs = repository.analysis_runs_for_submission(submission_id)
    if not runs:
        return {
            "submission_id": submission_id,
            "image_reference": image_reference,
            "analysis_available": False,
            "evidence_groups": {},
            "manual_actions": _manual_actions(),
        }

    run = runs[-1]
    score = run.score
    return {
        "submission_id": submission_id,
        "image_reference": image_reference,
        "analysis_available": True,
        "score": score.score if score else None,
        "band": score.band if score else None,
        "top_reasons": score.reasons if score else [],
        "evidence_groups": _group_evidence(run.evidence),
        "provider_status": _provider_status(run.evidence),
        "manual_actions": _manual_actions(),
    }


def _manual_actions() -> list[str]:
    return [
        ReviewStatus.APPROVED.value,
        ReviewStatus.HELD.value,
        ReviewStatus.REJECTED.value,
    ]


def _group_evidence(evidence: list[Evidence]) -> dict[str, list[dict[str, Any]]]:
    groups: dict[str, list[dict[str, Any]]] = {
        "internal": [],
        "naver": [],
        "google": [],
        "llm": [],
        "failures": [],
    }
    for item in evidence:
        groups[_group_name(item)].append(_present_evidence(item))
    return {key: value for key, value in groups.items() if value}


def _group_name(item: Evidence) -> str:
    if item.source in {EvidenceSource.FINGERPRINT, EvidenceSource.FACE_PERSON}:
        return "internal"
    if item.source == EvidenceSource.NAVER_SEARCH:
        return "naver"
    if item.source == EvidenceSource.WEB_DETECTION:
        return "google"
    if item.source == EvidenceSource.LLM_SUMMARY:
        return "llm"
    return "failures"


def _present_evidence(item: Evidence) -> dict[str, Any]:
    return {
        "source": item.source,
        "reason": item.reason,
        "confidence": item.confidence,
        "data": item.data,
    }


def _provider_status(evidence: list[Evidence]) -> dict[str, list[str]]:
    status: dict[str, list[str]] = {}
    for item in evidence:
        if item.source in {
            EvidenceSource.EXTERNAL_SKIPPED,
            EvidenceSource.SEARCH_SKIPPED,
            EvidenceSource.FAILURE,
            EvidenceSource.ENRICHMENT_FAILURE,
        }:
            provider = str(item.data.get("provider", item.source.value))
            status.setdefault(provider, []).append(item.reason)
    return status
