# src/fmatch/saas/api/v2/match.py
from fastapi import APIRouter
from pydantic import BaseModel
from typing import Optional

router = APIRouter(prefix="/api/v2/match", tags=["match"])


class PairExplain(BaseModel):
    mode: str  # 'l2a' | 'dedupe'
    object_type: Optional[str] = None  # for dedupe
    source_id: str
    target_id: str


@router.post("/explain-pair")
async def explain_pair(body: PairExplain):
    # Reuse the same engine/explainer used for ExplainModal by calling a pair scorer,
    # return { match_score, tier, match_type, evidence_count, evidence_strength, evidence_flags, field_score_details[] }.
    # Mirrors explainMatch(id) response shape used in ExplainModal.

    # TODO: Implement actual pair scoring using engine
    # For now, return mock response that matches ExplainModal expectations
    import random

    score = random.uniform(0.65, 0.95)
    tier = "CERTAIN" if score > 0.85 else "LIKELY" if score > 0.75 else "POSSIBLE"

    return {
        "match_score": score,
        "tier": tier,
        "match_type": "fuzzy",
        "evidence_count": 3,
        "evidence_strength": score * 0.9,
        "evidence_flags": ["name->name", "email->email"],
        "ensemble_used": True,
        "field_score_details": [
            {
                "source_field": "name",
                "reference_field": "name",
                "score": score * 100,
                "algorithm": "TokenSetRatio",
                "weight": 0.4,
            },
            {
                "source_field": "email",
                "reference_field": "email",
                "score": (score * 0.8) * 100,
                "algorithm": "Domain",
                "weight": 0.3,
            },
        ],
    }
