# backend/app/routers/approvals.py
from fastapi import APIRouter, Depends, HTTPException
from sqlmodel import Session, select

from ..approvals import service
from ..auth.deps import current_user
from ..db import get_session
from ..models import Approval, ApprovalLog, Person
from ..schemas import (
    ApprovalLogOut,
    ApprovalOut,
    ApprovalQueueOut,
    AutonomyOut,
    AutonomyPatch,
)

router = APIRouter()  # prefix 없음. main.py 에서 prefix="/api" 등록.

SAVED_TODAY = "47분"  # 원본 approve-data.js savedToday
AUTO_COUNT_NIGHT = 7  # 원본 autoCountNight


def _out(a: Approval) -> ApprovalOut:
    return ApprovalOut(
        id=a.id,
        icon=a.icon,
        tone=a.tone,
        risk=a.risk,
        time=a.time,
        title=a.title,
        detail=a.detail,
        cta=a.cta,
        alt=a.alt,
        undo_label=a.undo_label,
        status=a.status,
        source=a.source,
        rule_id=a.rule_id,
        sort_order=a.sort_order,
    )


@router.get("/approvals", response_model=ApprovalQueueOut)
def get_queue(s: Session = Depends(get_session), user: Person = Depends(current_user)):
    q = service.derive_queue(s, user_id=user.id)
    logs = s.exec(select(ApprovalLog).order_by(ApprovalLog.sort_order)).all()
    return ApprovalQueueOut(
        autonomy=q["level"],
        saved_today=SAVED_TODAY,
        auto_count_night=AUTO_COUNT_NIGHT,
        pending=[_out(a) for a in q["pending"]],
        done=[_out(a) for a in q["done"]],
        log=[
            ApprovalLogOut(id=log.id, time=log.time, text=log.text, approval_id=log.approval_id)
            for log in logs
        ],
        badges_appr=len(q["pending"]),
    )


@router.post("/approvals/approve-all")
def approve_all(s: Session = Depends(get_session)):
    return {"approved": service.approve_all(s)}


@router.get("/approvals/autonomy", response_model=AutonomyOut)
def get_autonomy(s: Session = Depends(get_session)):
    return AutonomyOut(level=service.get_autonomy(s))


@router.get("/approvals/{aid}", response_model=ApprovalOut)
def get_one(aid: str, s: Session = Depends(get_session)):
    a = s.get(Approval, aid)
    if not a:
        raise HTTPException(404, "approval not found")
    return _out(a)


@router.patch("/approvals/autonomy", response_model=AutonomyOut)
def set_autonomy(body: AutonomyPatch, s: Session = Depends(get_session)):
    try:
        return AutonomyOut(level=service.set_autonomy(s, body.level))
    except ValueError as e:
        raise HTTPException(422, str(e)) from e


@router.post("/approvals/{aid}/approve", response_model=ApprovalOut)
def approve(aid: str, s: Session = Depends(get_session)):
    if not s.get(Approval, aid):
        raise HTTPException(404, "approval not found")
    return _out(service.approve(s, aid))


@router.post("/approvals/{aid}/execute", response_model=ApprovalOut)
def execute(aid: str, s: Session = Depends(get_session)):
    if not s.get(Approval, aid):
        raise HTTPException(404, "approval not found")
    return _out(service.approve(s, aid))  # high-risk cta 실행 = approve 와 동일 전이


@router.post("/approvals/{aid}/undo", response_model=ApprovalOut)
def undo(aid: str, s: Session = Depends(get_session)):
    if not s.get(Approval, aid):
        raise HTTPException(404, "approval not found")
    return _out(service.undo(s, aid))
