from __future__ import annotations
from fastapi import APIRouter, Form
from fastapi.responses import RedirectResponse
from app.web.deps import sb

router = APIRouter()

@router.post("/sync/decide", response_class=RedirectResponse)
async def sync_decide(
    batch_id: str = Form(...),
    staging_id: int = Form(...),
    choice: str = Form(...),  # "__NEW__" | "__SKIP__" | "<person_id>"
):
    decision = "MANUAL"; person_id = None; score = 1.0; rationale = None
    if choice == "__NEW__":
        rationale = "manual-new"
    elif choice == "__SKIP__":
        decision = "SKIP"; score = 0.0; rationale = "manual-skip"
    else:
        try: person_id = int(choice)
        except Exception: person_id = None

    payload = {
        "batch_id": batch_id, "staging_id": staging_id, "decision": decision,
        "person_id": person_id, "score": score, "rationale": rationale,
    }
    sb.table("match_decisions").upsert(payload, on_conflict="batch_id,staging_id").execute()
    return RedirectResponse(f"/sync/batch/{batch_id}?saved=1", status_code=302)
