"""Unit and integration test suite for AI Model Benchmark & Enterprise Agent Management."""

from __future__ import annotations

import pytest
from fastapi.testclient import TestClient

from app.main import create_app
from app.modules.auth.application.auth_service import AuthService
from app.modules.core.application.model_benchmark_service import ModelBenchmarkService


@pytest.fixture
def clean_client() -> TestClient:
    app = create_app()
    app.dependency_overrides = {}
    return TestClient(app)


@pytest.fixture
def superadmin_headers() -> dict[str, str]:
    auth = AuthService()
    token = auth.create_jwt_token(
        {
            "id": "superadmin-test-id",
            "email": "son.dinhson@dscons.vn",
            "role": "superadmin",
            "full_name": "Nguyễn Sĩ Sơn",
            "company_id": "0202111150",
        }
    )
    return {"Authorization": f"Bearer {token}"}


@pytest.fixture
def viewer_headers() -> dict[str, str]:
    auth = AuthService()
    token = auth.create_jwt_token(
        {
            "id": "viewer-test-id",
            "email": "viewer@dscons.vn",
            "role": "viewer",
            "full_name": "Viewer Test",
            "company_id": "0202111150",
        }
    )
    return {"Authorization": f"Bearer {token}"}


# --------------------------------------------------------------------------
# UNIT TESTS (BENCHMARK SERVICE LEVEL)
# --------------------------------------------------------------------------
def test_model_benchmark_service_execution():
    """Kiểm thử bài benchmark đo lường Latency, TPS và Điểm chất lượng."""
    service = ModelBenchmarkService()
    results = service.run_benchmark()

    assert len(results) >= 4
    providers = {r["provider"] for r in results}
    assert "openrouter" in providers
    assert "lmstudio" in providers
    assert "antigravity_sdk" in providers

    for r in results:
        assert r["ttft_ms"] > 0
        assert r["tps"] > 0
        assert r["quality_score"] >= 80.0
        assert r["cost_per_million_tokens"] == 0.0  # 100% Free
        assert r["status"] == "HEALTHY"


def test_model_recommendations_for_all_9_personas():
    """Kiểm thử thuật toán ghép model tối ưu cho 9 nhân sự AI."""
    service = ModelBenchmarkService()
    recs = service.generate_recommendations()

    assert len(recs) == 9
    rec_dict = {r["agent_code"]: r for r in recs}

    # 1. Thảo (Pháp chế) -> Gemini 3.1 Pro (Pháp lý Luật Xây dựng 2025 cao nhất)
    assert rec_dict["thao"]["recommended_model"] == "gemini-3.1-pro"
    assert rec_dict["thao"]["quality_score"] >= 98.0

    # 2. Quỳnh (Dự toán BOQ) -> Gemini 3.1 Pro (Bóc tách dự toán & số học)
    assert rec_dict["quynh"]["recommended_model"] == "gemini-3.1-pro"
    assert rec_dict["quynh"]["quality_score"] >= 97.0

    # 3. Nam (Kế toán trưởng) -> Gemini 3.8 Flash (Tốc độ, đối soát dòng tiền & Vibe Coding)
    assert rec_dict["nam"]["recommended_model"] == "gemini-3.8-flash"
    assert rec_dict["nam"]["tps"] >= 70.0

    # 4. Phúc (Chỉ huy trưởng) -> Antigravity SDK (Tốc độ cao, điều phối hiện trường)
    assert rec_dict["phuc"]["recommended_provider"] == "antigravity_sdk"
    assert rec_dict["phuc"]["recommended_model"] == "gemini-3.8-flash"


def test_apply_optimal_recommendations_execution():
    """Kiểm thử 1-Click áp dụng toàn bộ đề xuất mô hình tối ưu."""
    service = ModelBenchmarkService()
    res = service.apply_optimal_recommendations()

    assert res["success"] is True
    assert res["applied_count"] == 9
    assert res["total_agents"] == 9
    assert len(res["details"]) == 9


# --------------------------------------------------------------------------
# INTEGRATION TESTS (REST API & RBAC)
# --------------------------------------------------------------------------
def test_benchmark_api_endpoints_authorized(
    clean_client: TestClient, superadmin_headers: dict[str, str]
):
    """Kiểm thử các API endpoints của Model Benchmark với quyền Superadmin."""
    # 1. POST /v1/admin/model-benchmark/run
    res1 = clean_client.post(
        "/v1/admin/model-benchmark/run", headers=superadmin_headers
    )
    assert res1.status_code == 200
    data1 = res1.json()
    assert data1["status"] == "SUCCESS"
    assert data1["tested_models_count"] >= 4

    # 2. GET /v1/admin/model-benchmark/results
    res2 = clean_client.get(
        "/v1/admin/model-benchmark/results", headers=superadmin_headers
    )
    assert res2.status_code == 200
    assert res2.json()["tested_models_count"] >= 4

    # 3. GET /v1/admin/model-benchmark/recommendations
    res3 = clean_client.get(
        "/v1/admin/model-benchmark/recommendations", headers=superadmin_headers
    )
    assert res3.status_code == 200
    assert res3.json()["total_personas"] == 9

    # 4. POST /v1/admin/model-benchmark/apply-recommendations
    res4 = clean_client.post(
        "/v1/admin/model-benchmark/apply-recommendations", headers=superadmin_headers
    )
    assert res4.status_code == 200
    assert res4.json()["success"] is True


def test_benchmark_api_endpoints_forbidden_for_viewer(
    clean_client: TestClient, viewer_headers: dict[str, str]
):
    """Kiểm thử quyền Viewer bị từ chối 403 khi cố chạy benchmark hoặc áp dụng model."""
    res1 = clean_client.post("/v1/admin/model-benchmark/run", headers=viewer_headers)
    assert res1.status_code == 403

    res2 = clean_client.post(
        "/v1/admin/model-benchmark/apply-recommendations", headers=viewer_headers
    )
    assert res2.status_code == 403


def test_stealth_model_lifecycle_and_auto_fallback(
    clean_client: TestClient, superadmin_headers: dict[str, str]
):
    """Kiểm thử chu trình tự động chuyển đổi Fallback khi mô hình Stealth hết hạn."""
    from datetime import datetime, timedelta, timezone

    from app.core.postgres.erp_client import ErpDatabaseClient
    from app.core.settings import get_settings
    from app.modules.agents.application.llm_client import LLMClient

    db = ErpDatabaseClient()
    settings = get_settings()

    # 1. Cấu hình nhân viên 'thuy' dùng stealth/ox-alpha với hạn hết từ ngày hôm qua
    past_date = (datetime.now(timezone.utc) - timedelta(days=1)).isoformat()
    db.update_ai_agent_model(
        agent_code="thuy",
        model_name="stealth/ox-alpha",
        provider="openrouter",
        is_stealth_promo=True,
        stealth_expires_at=past_date,
        fallback_model_name="google/gemini-2.0-flash-exp:free",
        fallback_provider="openrouter",
    )

    # 2. LLMClient khi gọi get_provider_for_agent("thuy") phải tự động nhận diện hết hạn và dùng fallback
    client = LLMClient(settings)
    provider_info = client.get_provider_for_agent("thuy")
    assert provider_info["model"] == "google/gemini-2.0-flash-exp:free"
    assert provider_info["provider"] == "openrouter"

    # 3. Kích hoạt API quét hết hạn Stealth
    res = clean_client.post(
        "/v1/admin/model-benchmark/check-stealth-expiration", headers=superadmin_headers
    )
    assert res.status_code == 200
    data = res.json()
    assert data["success"] is True

    # 4. Kiểm tra trong DB xem 'thuy' đã được chuyển về fallback vĩnh viễn chưa
    thuy_model = db.get_ai_agent_model("thuy")
    assert thuy_model is not None
    assert thuy_model["model_name"] == "google/gemini-2.0-flash-exp:free"
    assert thuy_model["is_stealth_promo"] is False


def test_agent_management_dashboard_html_page(clean_client: TestClient):
    """Kiểm thử trang giao diện Quản trị AI Models và DHS tải thành công và có đầy đủ thành phần."""
    res = clean_client.get("/dashboard/agent-models")
    assert res.status_code == 200
    assert "text/html" in res.headers.get("content-type", "")
    assert "Quản Trị AI Models" in res.text
    assert "Bảng So Sánh Hiệu Năng" in res.text
    assert "Ma Trận Phân Bổ Tối Ưu" in res.text
    assert "Stealth" in res.text

    # Kiểm tra route /dashboard/dhs và /dhs tích hợp vào ERP
    res_dhs = clean_client.get("/dashboard/dhs")
    assert res_dhs.status_code == 200
    assert "Phòng Điều Hành Tác Vụ Tự Trị" in res_dhs.text
    assert "DeepSeek Agentic Harness" in res_dhs.text

    # Removed check for /dhs and /v1/erp/dashboard/dhs since they are merged
