"""
Telegram Webhook Handler — ADR-094 / ADR-095
=============================================
接收 Telegram Bot API 的 webhook push，支援 secret_token 驗證。
WS4 Hermes NL 接入：@mention 觸發 12-Agent 自然語言問答。

2026-04-24 Claude Sonnet 4.6 (ADR-093 WS3 / ADR-094)
2026-04-24 Claude Sonnet 4.6 (ADR-095 WS4 Hermes NL 接入)
"""
from __future__ import annotations

from typing import Optional

import structlog
from fastapi import APIRouter, Depends, Header, HTTPException, Request

from src.core.config import settings

logger = structlog.get_logger(__name__)

router = APIRouter(prefix="/telegram", tags=["Telegram Webhook"])


def _verify_secret_token(
    x_telegram_bot_api_secret_token: Optional[str] = Header(None),
) -> None:
    """
    驗證 Telegram Webhook Secret Token（ADR-094 P0-2 修）

    若 TELEGRAM_WEBHOOK_SECRET 未配置（空字串）→ 跳過驗證（dev 環境相容）。
    生產環境必須配置此 secret，與 setWebhook 呼叫時的 secret_token 相同。
    """
    expected = getattr(settings, "TELEGRAM_WEBHOOK_SECRET", "")
    if not expected:
        # dev 環境：未配置 secret → 跳過驗證
        return
    if x_telegram_bot_api_secret_token != expected:
        logger.warning(
            "telegram_webhook_invalid_secret",
            provided=bool(x_telegram_bot_api_secret_token),
        )
        raise HTTPException(status_code=403, detail="Invalid webhook secret")


@router.post("/webhook", dependencies=[Depends(_verify_secret_token)])
async def telegram_webhook(request: Request) -> dict:
    """
    接收 Telegram Bot API webhook update。

    目前：記錄 update 類型 + 回傳 200 OK。
    WS4 Hermes NL：在此呼叫 Hermes NL router 處理自然語言指令。

    Telegram Bot API 要求此端點在 1 秒內回傳 200，耗時操作須非同步排程。
    """
    body = await request.json()

    if "message" in body:
        update_type = "message"
    elif "callback_query" in body:
        update_type = "callback_query"
    elif "edited_message" in body:
        update_type = "edited_message"
    elif "channel_post" in body:
        update_type = "channel_post"
    else:
        update_type = "other"

    logger.info(
        "telegram_webhook_received",
        update_type=update_type,
        update_id=body.get("update_id"),
    )

    if update_type == "callback_query":
        callback = body.get("callback_query", {}) or {}
        message = callback.get("message", {}) or {}
        user = callback.get("from", {}) or {}
        callback_query_id = callback.get("id")
        callback_data = callback.get("data")
        user_id = user.get("id")
        if callback_query_id and callback_data and user_id:
            from src.services.telegram_gateway import get_telegram_gateway

            gateway = get_telegram_gateway()
            mirror_callback = getattr(gateway, "mirror_callback_query_received", None)
            if callable(mirror_callback):
                await mirror_callback(
                    update_id=body.get("update_id"),
                    callback_query_id=callback_query_id,
                    callback_data=callback_data,
                    user_id=user_id,
                    username=user.get("username") or user.get("first_name") or str(user_id),
                    message_id=message.get("message_id"),
                    chat_id=(message.get("chat") or {}).get("id"),
                )

    # WS5: chat_member 同步 Approvers 白名單（ADR-093）
    if update_type in ("chat_member", "my_chat_member") or (
        "chat_member" in body or "my_chat_member" in body
    ):
        event = body.get("chat_member") or body.get("my_chat_member", {})
        if event:
            group_id = str(event.get("chat", {}).get("id", ""))
            member = event.get("new_chat_member", {})
            user = member.get("user", {})
            member_user_id = user.get("id", 0)
            status = member.get("status", "")
            if group_id and member_user_id:
                try:
                    from src.core.redis_client import get_redis  # type: ignore[import]
                    from src.hermes.approvers import sync_member_joined, sync_member_left  # type: ignore[import]
                    redis = get_redis()
                    if status in ("member", "administrator", "creator"):
                        await sync_member_joined(redis, group_id, member_user_id)
                    elif status in ("left", "kicked"):
                        await sync_member_left(redis, group_id, member_user_id)
                except Exception as exc:
                    logger.error("approvers_sync_error", error=str(exc))

    # WS4: Hermes NL 接入（ADR-095）
    # 只在 HERMES_NL_ENABLED=true 且 update_type=message 時處理
    if update_type == "message" and settings.HERMES_NL_ENABLED:
        msg = body.get("message", {})
        text = msg.get("text", "")
        chat_id = str(msg.get("chat", {}).get("id", ""))
        from_user = msg.get("from", {})
        user_id = from_user.get("id", 0)
        username = from_user.get("username", "")

        bot_username = settings.TELEGRAM_BOT_USERNAME
        # 觸發條件：@mention 或私訊（私訊的 chat.type == "private"）
        chat_type = msg.get("chat", {}).get("type", "")
        is_mention = f"@{bot_username}" in text
        is_private = chat_type == "private"
        message_id: int | None = msg.get("message_id")

        if (is_mention or is_private) and text.strip():
            clean_text = text.replace(f"@{bot_username}", "").strip()
            if clean_text:
                # 延遲 import 避免啟動時副作用（SDK / structlog 初始化）
                from src.hermes.nl_gateway import process_nl_message
                from src.services.telegram_gateway import get_telegram_gateway

                try:
                    reply = await process_nl_message(
                        clean_text,
                        chat_id=chat_id,
                        user_id=user_id,
                        username=username,
                    )
                    gw = get_telegram_gateway()
                    # send_hermes_reply：長文純文字，reply-to 原始訊息
                    await gw.send_hermes_reply(
                        text=reply,
                        chat_id=chat_id,
                        reply_to_message_id=message_id,
                    )
                except Exception as exc:
                    logger.error(
                        "telegram_webhook_hermes_error",
                        error=str(exc),
                        chat_id=chat_id,
                        user_id=user_id,
                    )

    return {"ok": True}
