"""Copilot API — 분석, 질의, 액션 실행."""

import json
import logging

from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse, StreamingResponse

from sentinel.services.copilot_service import CopilotContext

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


@router.post("/analyze")
async def copilot_analyze(request: Request):
    """context를 분석하고 summary + recommended actions를 반환합니다."""
    body = await request.json()
    ctx = CopilotContext(
        surface_type=body.get("surface_type", ""),
        object_id=body.get("object_id", ""),
        object_metadata=body.get("object_metadata", {}),
        evidence_refs=body.get("evidence_refs", []),
        allowed_actions=body.get("allowed_actions", []),
    )

    copilot = request.app.state.services.copilot
    try:
        result = copilot.analyze(ctx)
        return JSONResponse(result.to_dict())
    except Exception as e:
        logger.exception("Copilot analyze 실패")
        return JSONResponse({"error": str(e)}, status_code=500)


@router.post("/ask")
async def copilot_ask(request: Request):
    """context + question으로 SSE 스트리밍 응답을 반환합니다."""
    body = await request.json()
    question = body.get("question", "")
    ctx = CopilotContext(
        surface_type=body.get("surface_type", ""),
        object_id=body.get("object_id", ""),
        object_metadata=body.get("object_metadata", {}),
        evidence_refs=body.get("evidence_refs", []),
    )

    copilot = request.app.state.services.copilot

    async def event_stream():
        try:
            result = copilot.ask(question, ctx)
            # 응답을 청크로 나누어 SSE 전송
            content = result.summary
            chunk_size = 50
            for i in range(0, len(content), chunk_size):
                chunk = content[i:i + chunk_size]
                yield f"data: {json.dumps({'type': 'token', 'content': chunk}, ensure_ascii=False)}\n\n"
            yield f"data: {json.dumps({'type': 'done'})}\n\n"
        except Exception as e:
            yield f"data: {json.dumps({'type': 'error', 'content': str(e)})}\n\n"

    return StreamingResponse(event_stream(), media_type="text/event-stream")


@router.post("/action/{action_id}")
async def copilot_action(request: Request, action_id: str):
    """추천 action을 실행합니다."""
    body = await request.json()
    ctx = CopilotContext(
        surface_type=body.get("surface_type", ""),
        object_id=body.get("object_id", ""),
        object_metadata=body.get("object_metadata", {}),
    )
    params = body.get("params", {})

    copilot = request.app.state.services.copilot
    try:
        result = copilot.execute_action(action_id, ctx, params)
        return JSONResponse(result.to_dict())
    except Exception as e:
        logger.exception("Copilot action 실행 실패: %s", action_id)
        return JSONResponse({"error": str(e)}, status_code=500)
