# Trinity Score: 95.0 (Discord Webhook Router)
import logging
from typing import Any

from fastapi import APIRouter, HTTPException, Request

from AFO.services.unified_messaging_service import ChannelType, unified_messaging_service
from AFO.utils.standard_shield import shield

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/api/discord", tags=["Discord Bot Bridge"])


@shield(pillar="善")
@router.post("/webhook")
async def discord_webhook(request: Request) -> dict[str, Any]:
    """디스코드 메시지를 수신하여 통합 서비스로 전달."""
    try:
        payload = await request.json()

        msg = payload.get("msg", "")
        sender = payload.get("sender", "알 수 없음")

        result = await unified_messaging_service.handle_incoming_message(
            content=msg, sender=sender, channel=ChannelType.DISCORD
        )
        return result
    except Exception as e:
        logger.error("Discord Webhook Error: %s", e)
        raise HTTPException(status_code=500, detail=str(e)) from e


@shield(pillar="善")
@router.get("/status")
async def get_discord_status() -> dict[str, Any]:
    """디스코드 브릿지 상태 확인."""
    return {
        "bot_status": "active",
        "bridge_version": "1.0.0",
        "supported_commands": ["!상태", "!도움", "승상, 질문"],
    }
