"""Improvement Loop 라우트 — Draft 관리 + 승인 연결."""

import logging

from fastapi import APIRouter, Request, Form
from fastapi.responses import HTMLResponse, RedirectResponse

from sentinel.schema import AuditEvent, ActionType, Surface

router = APIRouter(prefix="/improvement", tags=["improvement"])
logger = logging.getLogger("sentinel.web.improvement")


@router.get("/drafts", response_class=HTMLResponse)
async def page_drafts(request: Request):
    """Draft artifact 목록."""
    from sentinel.services.draft_store import draft_store

    drafts = draft_store.list_drafts(limit=100)
    pending = [d for d in drafts if d["review_status"] == "pending"]
    approved = [d for d in drafts if d["review_status"] == "approved"]
    rejected = [d for d in drafts if d["review_status"] == "rejected"]

    return request.app.state.templates.TemplateResponse(request, "drafts.html", {
        "drafts": drafts,
        "pending_count": len(pending),
        "approved_count": len(approved),
        "rejected_count": len(rejected),
        "active_page": "improvement",
    })


@router.get("/drafts/{draft_id}", response_class=HTMLResponse)
async def page_draft_detail(request: Request, draft_id: str):
    """Draft 상세 — evidence refs, 내용, approve 버튼."""
    from sentinel.services.draft_store import draft_store

    draft = draft_store.get(draft_id)
    if not draft:
        return HTMLResponse("<h1>Draft not found</h1>", status_code=404)

    return request.app.state.templates.TemplateResponse(request, "draft_detail.html", {
        "draft": draft,
        "draft_id": draft_id,
        "active_page": "improvement",
    })


@router.post("/drafts/{draft_id}/approve")
async def approve_draft(request: Request, draft_id: str):
    """Draft를 승인하고 approval에 연결합니다."""
    from sentinel.services.draft_store import draft_store
    from sentinel.services.governance import governance

    draft = draft_store.get(draft_id)
    if not draft:
        return HTMLResponse("<h1>Draft not found</h1>", status_code=404)

    # Approval 생성
    from sentinel.schema import ApprovalRequest
    req = ApprovalRequest(
        request_type=f"draft_{draft['data'].get('type', 'unknown')}",
        action_summary=f"Draft 승인: {draft_id} ({draft['data'].get('type', '')})",
        params={"draft_id": draft_id},
        actor=getattr(request.state, "user", None) or "unknown",
        surface=Surface.WEB,
    )
    approval_id = governance.require_approval(req)
    draft_store.update_status(draft_id, "approved", approval_id=approval_id)

    governance.record_action(AuditEvent(
        action=f"approve_draft:{draft_id}",
        action_type=ActionType.MUTATE,
        actor=getattr(request.state, "user", None) or "unknown",
        surface=Surface.WEB,
        target_refs=[draft_id],
        is_mutation=True,
    ))

    return RedirectResponse(url=f"/improvement/drafts/{draft_id}", status_code=303)


@router.post("/drafts/{draft_id}/reject")
async def reject_draft(request: Request, draft_id: str):
    """Draft를 거절합니다."""
    from sentinel.services.draft_store import draft_store
    from sentinel.services.governance import governance

    draft_store.update_status(draft_id, "rejected")

    governance.record_action(AuditEvent(
        action=f"reject_draft:{draft_id}",
        action_type=ActionType.MUTATE,
        actor=getattr(request.state, "user", None) or "unknown",
        surface=Surface.WEB,
        target_refs=[draft_id],
        is_mutation=True,
    ))

    return RedirectResponse(url="/improvement/drafts", status_code=303)
