"""Comprehensive Unit & Integration Test Suite for DSCons Telegram Suite."""

import asyncio

import pytest
from fastapi.testclient import TestClient

from app.main import app
from app.models.telegram_schemas import (
    TelegramAlertSeverity,
    TelegramAlertType,
    TelegramServiceStatus,
)
from app.modules.integrations.application.telegram_service import TelegramService


@pytest.fixture
def client(monkeypatch) -> TestClient:
    import app.modules.integrations.presentation.telegram_routes as tr
    from app.core.settings import get_settings

    settings = get_settings()
    monkeypatch.setattr(settings, "telegram_bot_token", None)
    monkeypatch.setattr(tr.telegram_service, "bot_token", "")
    return TestClient(app)


@pytest.fixture
def telegram_service(monkeypatch) -> TelegramService:
    monkeypatch.setenv("TELEGRAM_BOT_TOKEN", "")
    return TelegramService(bot_token="")


def test_telegram_service_status(telegram_service: TelegramService):
    status = telegram_service.get_status()
    assert isinstance(status, TelegramServiceStatus)
    assert status.enabled is True
    assert "/nhatky" in status.supported_commands
    assert "/duan" in status.supported_commands
    assert "/camay" in status.supported_commands
    assert "/ai" in status.supported_commands


def test_telegram_send_message_simulation(telegram_service: TelegramService):
    res = asyncio.run(
        telegram_service.send_message(
            text="<b>Test DSCons ERP Notification</b>",
            chat_id="test_channel_123",
        )
    )
    assert res.ok is True
    assert res.status == "simulated_success"
    assert "mock-msg-" in str(res.message_id)


def test_telegram_send_alert(telegram_service: TelegramService):
    res = asyncio.run(
        telegram_service.send_alert(
            title="Vượt Ngân Sách Hạng Mục Đào Đất WBS 2.1",
            alert_type=TelegramAlertType.EVM_VARIANCE,
            severity=TelegramAlertSeverity.WARNING,
            project_name="PILOT-NAM-HK-2026",
            details=[
                "Chi phí thực tế AC: 185.000.000 ₫",
                "Giá trị thu được EV: 160.000.000 ₫",
                "CPI: 0.86 (< 1.0)",
            ],
            action_url="https://dinhsonconstruction.com/dashboard/projects",
        )
    )
    assert res.ok is True
    assert res.status == "simulated_success"


def test_telegram_send_site_diary_report(telegram_service: TelegramService):
    res = asyncio.run(
        telegram_service.send_site_diary_report(
            project_code="PILOT-NAM-HK-2026",
            project_name="Cụm cấp nước & Trạm bơm Nam Hưng",
            shift_date="2026-08-22",
            weather="Nắng ráo 33°C",
            workforce_count=34,
            machine_count=4,
            activities=[
                "WBS 2.1: Hoàn thành đào hố móng",
                "WBS 2.3: Đổ bê tông móng thương phẩm M300",
            ],
            supervisor_notes="Chất lượng bê tông đạt yêu cầu, độ sụt 12cm",
        )
    )
    assert res.ok is True
    assert res.status == "simulated_success"


def test_telegram_process_commands(telegram_service: TelegramService):
    # Test /start
    res_start = asyncio.run(
        telegram_service.process_command("/start", user_name="Quân")
    )
    assert "Xin chào Quân" in res_start
    assert "/duan" in res_start

    # Test /help
    res_help = asyncio.run(telegram_service.process_command("/help"))
    assert "HƯỚNG DẪN SỬ DỤNG TELEGRAM SUITE" in res_help

    # Test /duan
    res_duan = asyncio.run(telegram_service.process_command("/duan"))
    assert "PILOT-NAM-HK-2026" in res_duan
    assert "DA-KIENMINH-2026" in res_duan

    # Test /camay
    res_camay = asyncio.run(telegram_service.process_command("/camay"))
    assert "Volvo EW140E" in res_camay
    assert "Thaco Auto" in res_camay

    # Test /hoadon
    res_hoadon = asyncio.run(telegram_service.process_command("/hoadon"))
    assert "106 Hóa đơn" in res_hoadon

    # Test /nhatky
    res_nhatky = asyncio.run(
        telegram_service.process_command(
            "/nhatky Hôm nay trời nắng 34 độ 28 thợ 3 ca máy đổ bê tông móng M300 lấy 03 tổ mẫu"
        )
    )
    assert "AI BÓC TÁCH NHẬT KÝ CÔNG TRƯỜNG THÀNH CÔNG" in res_nhatky
    assert "28 Nhân sự" in res_nhatky
    assert "M300" in res_nhatky

    # Test /warroom
    res_warroom = asyncio.run(telegram_service.process_command("/warroom"))
    assert "EXECUTIVE FINANCIAL WAR ROOM" in res_warroom
    assert "Ngày An Toàn" in res_warroom

    # Test /vattu (MR)
    res_vattu = asyncio.run(
        telegram_service.process_command("/vattu 45m3 cát vàng bãi đúc cống")
    )
    assert "ĐÃ KHỞI TẠO PHIẾU YÊU CẦU CẤP VẬT TƯ" in res_vattu
    assert "45m3 cát vàng" in res_vattu

    # Test /telematics
    res_telematics = asyncio.run(telegram_service.process_command("/telematics"))
    assert "QUẢN LÝ NHIÊN LIỆU & ĐỊNH MỨC CA MÁY" in res_telematics
    assert "Lít/Giờ" in res_telematics

    # Test /doisoat
    res_doisoat = asyncio.run(telegram_service.process_command("/doisoat"))
    assert "BÁO CÁO ĐỐI SOÁT 3 CHIỀU" in res_doisoat
    assert "Khớp nối hoàn hảo" in res_doisoat

    # Test /ai
    res_ai = asyncio.run(
        telegram_service.process_command("/ai Tiêu chuẩn bảo dưỡng bê tông")
    )
    assert "AI Chuyên Gia Kỹ Thuật" in res_ai
    assert "Luật Xây dựng 2025" in res_ai


def test_telegram_webhook_handling(telegram_service: TelegramService):
    update_payload = {
        "update_id": 10001,
        "message": {
            "message_id": 501,
            "from": {"id": 123456, "first_name": "Quỳnh", "username": "quynh_qs"},
            "chat": {"id": 123456, "type": "private"},
            "text": "/duan",
        },
    }
    res = asyncio.run(telegram_service.handle_webhook_update(update_payload))
    assert res.get("ok") is True
    assert res.get("status") == "processed"


def test_telegram_api_endpoints(client: TestClient):
    # 1. GET /v1/telegram/status
    res_status = client.get("/v1/telegram/status")
    assert res_status.status_code == 200
    data_status = res_status.json()
    assert data_status.get("enabled") is True
    assert "/nhatky" in data_status.get("supported_commands")

    # 2. POST /v1/telegram/send-message
    res_msg = client.post(
        "/v1/telegram/send-message",
        json={"text": "Test message from API", "chat_id": "site_managers_group"},
    )
    assert res_msg.status_code == 200
    assert res_msg.json().get("ok") is True

    # 3. POST /v1/telegram/send-alert
    res_alert = client.post(
        "/v1/telegram/send-alert",
        json={
            "title": "Cảnh báo Hóa đơn có rủi ro thuế",
            "alert_type": "INVOICE_TAX_RISK",
            "severity": "CRITICAL",
            "project_name": "PILOT-NAM-HK-2026",
            "details": ["Nhà cung cấp MST 0101234567 nằm trong diện rủi ro"],
        },
    )
    assert res_alert.status_code == 200
    assert res_alert.json().get("ok") is True

    # 4. POST /v1/telegram/site-diary-notification
    res_diary = client.post(
        "/v1/telegram/site-diary-notification",
        json={
            "project_code": "PILOT-NAM-HK-2026",
            "project_name": "Cụm cấp nước Nam Hưng",
            "shift_date": "2026-08-22",
            "weather": "Nắng ráo",
            "workforce_count": 30,
            "machine_count": 3,
            "activities": ["Đào đất móng", "Lắp đặt cốt thép"],
        },
    )
    assert res_diary.status_code == 200
    assert res_diary.json().get("ok") is True

    # 5. POST /v1/telegram/process-command
    res_cmd = client.post(
        "/v1/telegram/process-command",
        json={"command": "/camay", "user_name": "Hưng"},
    )
    assert res_cmd.status_code == 200
    assert "ĐỘI MÁY CƠ GIỚI" in res_cmd.json().get("reply")

    # 6. POST /v1/telegram/webhook
    res_webhook = client.post(
        "/v1/telegram/webhook",
        json={
            "message": {
                "from": {"first_name": "Minh"},
                "chat": {"id": 9999},
                "text": "/help",
            }
        },
    )
    assert res_webhook.status_code == 200
    assert res_webhook.json().get("ok") is True
