from __future__ import annotations

from typing import Any

from rights_filter.domain.records import (
    InMemoryRightsFilterRepository,
    OperatorDecision,
    ReviewStatus,
)


def operator_summary_for(
    repository: InMemoryRightsFilterRepository, submission_id: str
) -> dict[str, Any]:
    runs = repository.analysis_runs_for_submission(submission_id)
    if not runs:
        return {"submission_id": submission_id, "analysis": None}
    run = runs[-1]
    return {
        "submission_id": submission_id,
        "score": run.score.score if run.score else None,
        "band": run.score.band if run.score else None,
        "reasons": run.score.reasons if run.score else [],
        "evidence": [
            {
                "source": item.source,
                "reason": item.reason,
                "confidence": item.confidence,
                "data": item.data,
            }
            for item in run.evidence
        ],
    }


def applicant_summary_for(
    repository: InMemoryRightsFilterRepository, submission_id: str
) -> dict[str, Any]:
    return {"submission_id": submission_id}


def record_operator_decision(
    repository: InMemoryRightsFilterRepository,
    submission_id: str,
    status: ReviewStatus,
    memo: str = "",
    fingerprints: list[str] | None = None,
) -> OperatorDecision:
    decision = OperatorDecision.create(
        submission_id=submission_id,
        status=status,
        memo=memo,
    )
    repository.save_operator_decision(decision)

    if status == ReviewStatus.REJECTED:
        repository.create_rejected_image_entry(
            decision_id=decision.id,
            submission_id=submission_id,
            fingerprints=fingerprints or [],
        )

    return decision
