"""Telegram Enterprise Suite REST API endpoints."""

from __future__ import annotations

from typing import Any

from fastapi import APIRouter, Header, HTTPException, status

from app.core.settings import get_settings
from app.models.telegram_schemas import (
    TelegramAlertRequest,
    TelegramProcessCommandRequest,
    TelegramResponse,
    TelegramSendMessageRequest,
    TelegramServiceStatus,
    TelegramSiteDiaryNotificationRequest,
)
from app.modules.integrations.application.telegram_service import TelegramService

router = APIRouter(prefix="/v1/telegram", tags=["Telegram Suite"])
telegram_service = TelegramService()


@router.get("/status", response_model=TelegramServiceStatus)
async def get_telegram_status() -> TelegramServiceStatus:
    """Return the operational status of the Telegram Bot & Notification Gateway."""
    return telegram_service.get_status()


@router.post("/send-message", response_model=TelegramResponse)
async def send_telegram_message(
    payload: TelegramSendMessageRequest,
) -> TelegramResponse:
    """Send an arbitrary text message or HTML card to Telegram."""
    return await telegram_service.send_message(
        text=payload.text,
        chat_id=payload.chat_id,
        parse_mode=payload.parse_mode,
        disable_web_page_preview=payload.disable_web_page_preview,
        reply_markup=payload.reply_markup,
    )


@router.post("/send-alert", response_model=TelegramResponse)
async def send_telegram_alert(payload: TelegramAlertRequest) -> TelegramResponse:
    """Dispatch a structured enterprise alert card for EVM, Invoices, Quality, or Safety."""
    return await telegram_service.send_alert(
        title=payload.title,
        alert_type=payload.alert_type,
        severity=payload.severity,
        project_name=payload.project_name,
        details=payload.details,
        action_url=payload.action_url,
        chat_id=payload.chat_id,
    )


@router.post("/site-diary-notification", response_model=TelegramResponse)
async def send_site_diary_notification(
    payload: TelegramSiteDiaryNotificationRequest,
) -> TelegramResponse:
    """Broadcast daily site diary summary to site engineers and management."""
    return await telegram_service.send_site_diary_report(
        project_code=payload.project_code,
        project_name=payload.project_name,
        shift_date=payload.shift_date,
        weather=payload.weather,
        workforce_count=payload.workforce_count,
        machine_count=payload.machine_count,
        activities=payload.activities,
        supervisor_notes=payload.supervisor_notes,
        chat_id=payload.chat_id,
    )


@router.post("/process-command")
async def process_telegram_command(
    payload: TelegramProcessCommandRequest,
) -> dict[str, Any]:
    """Execute or simulate a Telegram command (/nhatky, /duan, /camay, /ai, /hoadon)."""
    reply = await telegram_service.process_command(
        command_text=payload.command,
        user_name=payload.user_name,
        chat_id=payload.chat_id,
        project_id=payload.project_id,
    )
    return {
        "ok": True,
        "command": payload.command,
        "reply": reply,
    }


@router.post("/webhook")
async def telegram_webhook(
    update: dict[str, Any],
    x_telegram_bot_api_secret_token: str | None = Header(default=None),
) -> dict[str, Any]:
    """Handle incoming Telegram webhook updates."""
    secret = get_settings().telegram_webhook_secret
    if (
        secret
        and x_telegram_bot_api_secret_token
        and x_telegram_bot_api_secret_token != secret
    ):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Invalid Telegram webhook secret token",
        )
    return await telegram_service.handle_webhook_update(update)
