from __future__ import annotations

from fastapi import APIRouter, Depends
from pydantic import BaseModel
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from ...db import get_session
from ...auth_security import require_account
from .l2a import make_role_dependency
from ...models import AutofillPolicy


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


class PolicyBody(BaseModel):
    l2a_enabled: bool = False
    c2a_enabled: bool = False
    l2a_threshold: float = 0.80
    c2a_threshold: float = 0.80
    min_score_gap: float = 0.05
    scope: str = "new_only"  # or 'new_and_backfill'
    new_window_hours: int = 48
    backfill_cap: int = 2000
    c2a_writeback_mode: str = "account"  # 'account'|'acr'
    b2c_skip: bool = True
    per_minute: int = 60
    daily_cap: int = 10000


@router.get("/policy")
async def get_policy(
    account_id: str = Depends(require_account),
    db: AsyncSession = Depends(get_session),
):
    row = (
        await db.execute(
            select(AutofillPolicy).where(AutofillPolicy.account_id == str(account_id))
        )
    ).scalar_one_or_none()
    if not row:
        row = AutofillPolicy(account_id=str(account_id))
        db.add(row)
        await db.commit()
        await db.refresh(row)
    # Return policy fields only
    return {
        "l2a_enabled": bool(row.l2a_enabled),
        "c2a_enabled": bool(row.c2a_enabled),
        "l2a_threshold": float(row.l2a_threshold or 0.80),
        "c2a_threshold": float(row.c2a_threshold or 0.80),
        "min_score_gap": float(row.min_score_gap or 0.05),
        "scope": str(row.scope or "new_only"),
        "new_window_hours": int(row.new_window_hours or 48),
        "backfill_cap": int(row.backfill_cap or 2000),
        "c2a_writeback_mode": str(row.c2a_writeback_mode or "account"),
        "b2c_skip": bool(row.b2c_skip),
        "per_minute": int(row.per_minute or 60),
        "daily_cap": int(row.daily_cap or 10000),
    }


require_admin_or_manager = make_role_dependency("admin", "manager")


@router.post("/policy", dependencies=[Depends(require_admin_or_manager)])
async def set_policy(
    body: PolicyBody,
    account_id: str = Depends(require_account),
    db: AsyncSession = Depends(get_session),
):
    row = (
        await db.execute(
            select(AutofillPolicy).where(AutofillPolicy.account_id == str(account_id))
        )
    ).scalar_one_or_none()
    if not row:
        row = AutofillPolicy(account_id=str(account_id))
    for k, v in body.model_dump().items():
        setattr(row, k, v)
    db.add(row)
    await db.commit()
    return {"ok": True}
