"""Unit and integration tests for DeepSeek Agentic Harness (DHS) Multi-Agent System."""

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.agents.application.deepseek_harness_service import DeepSeekHarnessService


@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 (SERVICE LEVEL)
# --------------------------------------------------------------------------
def test_dhs_sample_missions_catalogue():
    """Kiểm tra danh mục 4 kịch bản nhiệm vụ thực tế của DSCons."""
    service = DeepSeekHarnessService()
    samples = service.get_sample_missions()

    assert len(samples) == 5
    pillars = {s["pillar"] for s in samples}
    assert "xay_lap" in pillars
    assert "van_tai_xe_ben" in pillars
    assert "cho_thue_ca_may" in pillars
    assert "vat_tu_san_lap" in pillars
    assert "quan_tri_noi_bo" in pillars

    for s in samples:
        assert s["sample_id"].startswith("mission-")
        assert len(s["involved_personas"]) >= 3
        assert s["suggested_prompt"] != ""


def test_dhs_ground_truth_tools_execution():
    """Kiểm thử 6 công cụ Ground Truth được cung cấp cho AI Agents."""
    service = DeepSeekHarnessService()

    # 1. tool_hybrid_search_knowledge
    t1 = service.tool_hybrid_search_knowledge(query="bê tông cọc cừ larsen")
    assert t1["status"] == "SUCCESS"
    assert "execution_ms" in t1

    # 2. tool_query_erp_ledger
    t2 = service.tool_query_erp_ledger(entity_type="equipment")
    assert t2["status"] == "SUCCESS"
    assert t2["count"] >= 0

    # 3. tool_audit_3way_matching
    t3 = service.tool_audit_3way_matching()
    assert t3["status"] == "SUCCESS"
    assert "matching_result" in t3

    # 4. tool_boq_and_ipc_calculation
    t4 = service.tool_boq_and_ipc_calculation(project_id="DA-DADO-2026", stage_number=2)
    assert t4["status"] == "SUCCESS"
    assert "ipc_dossier" in t4

    # 5. tool_equipment_and_fuel_audit (Thoát Nước HP & Loan Khải)
    t5_transport = service.tool_equipment_and_fuel_audit(partner_vat_code="0200149705")
    assert t5_transport["status"] == "SUCCESS"
    t5_machinery = service.tool_equipment_and_fuel_audit(partner_vat_code="0201889988")
    assert t5_machinery["status"] == "SUCCESS"

    # 6. tool_legal_fidic_check
    t6 = service.tool_legal_fidic_check(project_name="Cống Bến Kem")
    assert t6["status"] == "SUCCESS"
    assert t6["compliance"]["validity_status"] == "COMPLIANT"


import asyncio

def test_dhs_mission_execution_xay_lap_ipc():
    """Kiểm thử chu trình điều phối tự trị lập hồ sơ Nghiệm thu Thanh toán IPC 03a Đợt 2."""
    service = DeepSeekHarnessService()
    res = asyncio.run(service.execute_mission(
        mission_title="Thẩm Định & Lập Hồ Sơ Nghiệm Thu Thanh Toán IPC Đợt 2 (Cống Bến Kem)",
        mission_prompt="Kiểm toán toàn diện khối lượng đắp đê bao, ép cọc cừ Larsen và bê tông cống Đợt 2.",
        pillar="xay_lap",
        deep_reasoning_enabled=True,
    ))

    assert res["status"] == "COMPLETED"
    assert res["mission_id"].startswith("DHS-")
    assert res["total_steps"] >= 1
    assert res["total_execution_seconds"] > 0

    # Xác thực Vòng phản biện chất lượng
    reflection = res["self_reflection_summary"]
    assert reflection["financial_precision_check"]["status"] in ["PASSED", "FAILED"]
    
    # Xác thực Báo cáo điều hành
    assert "BÁO CÁO" in res["executive_report"].upper()


def test_dhs_mission_execution_logistics_and_materials():
    """Kiểm thử kịch bản vận tải xe ben và mua bán vật tư."""
    service = DeepSeekHarnessService()

    # Kịch bản Trụ Cột 2: Vận tải xe ben
    res_transport = asyncio.run(service.execute_mission(
        mission_title="Kiểm toán 36 chuyến xe ben bùn nạo vét",
        mission_prompt="Đối soát vé cân và tiêu hao dầu 24L/h với Thoát Nước Hải Phòng.",
        pillar="van_tai_xe_ben",
    ))
    assert res_transport["status"] == "COMPLETED"
    assert res_transport["total_steps"] >= 1

    # Kịch bản Trụ Cột 4: Vật tư san lấp
    res_materials = asyncio.run(service.execute_mission(
        mission_title="Kiểm toán cát san lấp và mẫu R28",
        mission_prompt="Kiểm tra hao hụt ĐM 12/2021 và chứng chỉ chất lượng Trung Kiên.",
        pillar="vat_tu_san_lap",
    ))
    assert res_materials["status"] == "COMPLETED"
    assert res_materials["total_steps"] >= 1


# --------------------------------------------------------------------------
# INTEGRATION TESTS (REST API & RBAC)
# --------------------------------------------------------------------------
def test_dhs_api_endpoints_authorized(
    clean_client: TestClient, superadmin_headers: dict[str, str]
):
    """Kiểm thử các REST endpoints của DeepSeek Harness với quyền Superadmin."""
    # 1. GET /v1/agents/harness/sample-missions
    res1 = clean_client.get(
        "/v1/agents/harness/sample-missions", headers=superadmin_headers
    )
    assert res1.status_code == 200
    samples = res1.json()
    assert len(samples) == 5

    # 2. POST /v1/agents/harness/execute
    payload = {
        "mission_title": "Kiểm toán nghiệm thu giai đoạn 2 Cống Bến Kem",
        "mission_prompt": "Kiểm tra khối lượng và lập phụ lục 03a.",
        "pillar": "xay_lap",
        "deep_reasoning_enabled": True,
    }
    res2 = clean_client.post(
        "/v1/agents/harness/execute", json=payload, headers=superadmin_headers
    )
    if res2.status_code != 200:
        err_msg = str(res2.json()).encode("ascii", "backslashreplace").decode("ascii")
        raise AssertionError(f"POST /v1/agents/harness/execute failed: {err_msg}")
    data = res2.json()
    assert data["status"] == "COMPLETED"
    assert data["total_steps"] >= 1

    # 3. GET /v1/agents/harness/history
    res3 = clean_client.get("/v1/agents/harness/history", headers=superadmin_headers)
    assert res3.status_code == 200
    history = res3.json()
    assert "history" in history


def test_dhs_api_forbidden_for_unauthorized_execution(
    clean_client: TestClient, viewer_headers: dict[str, str]
):
    """Kiểm thử quyền Viewer bị từ chối 403 khi cố kích hoạt điều phối nhiệm vụ."""
    payload = {
        "mission_title": "Nhiệm vụ trái phép",
        "mission_prompt": "Thực thi trái phép.",
        "pillar": "xay_lap",
    }
    res = clean_client.post(
        "/v1/agents/harness/execute", json=payload, headers=viewer_headers
    )
    assert res.status_code == 403


# --------------------------------------------------------------------------
# MCP SERVER & AGENT WORK SHIFT SCHEDULER TESTS
# --------------------------------------------------------------------------
from app.mcp.dscons_mcp_server import DSConsMCPServer
from app.modules.agents.application.agent_scheduler_service import AgentSchedulerService


def test_dscons_mcp_server_protocol():
    """Kiểm thử MCP Server JSON-RPC 2.0 giao tiếp với DeepSeek Harness (DSH)."""
    server = DSConsMCPServer()

    # 1. Initialize
    init_res = server.handle_request(
        {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}
    )
    assert init_res["result"]["serverInfo"]["name"] == "dscons-erp-mcp"

    # 2. List tools
    list_res = server.handle_request(
        {"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}}
    )
    tools = list_res["result"]["tools"]
    tool_names = [t["name"] for t in tools]
    assert "search_dscons_knowledge" in tool_names
    assert "calculate_ipc_03a" in tool_names
    assert "audit_3way_matching" in tool_names

    # 3. Call tool: calculate_ipc_03a
    call_res = server.handle_request(
        {
            "jsonrpc": "2.0",
            "id": 3,
            "method": "tools/call",
            "params": {
                "name": "calculate_ipc_03a",
                "arguments": {
                    "project_id": "DA-KM-BENKEM-2025-2026",
                    "stage_number": 2,
                    "advance_deduction_pct": 10.0,
                    "retention_pct": 5.0,
                },
            },
        }
    )
    assert not call_res["result"]["isError"]
    content_text = call_res["result"]["content"][0]["text"]
    assert "certificate_code" in content_text


def test_agent_scheduler_shifts_and_anti_spam():
    """Kiểm thử phân ca so le và bộ đệm chống spam / rate limit."""
    scheduler = AgentSchedulerService()
    shifts = scheduler.get_daily_schedule()
    assert len(shifts) == 11

    # Kiểm tra ca trực của Phúc (offline LM studio) và Quỳnh (QS)
    phuc_shift = next(s for s in shifts if s["agent_code"] == "phuc")
    assert phuc_shift["preferred_provider"] == "lmstudio"

    quynh_shift = next(s for s in shifts if s["agent_code"] == "quynh")
    assert quynh_shift["preferred_model"] == "deepseek/deepseek-v4-pro"

    # Trạng thái Anti-Spam Shield
    shield = scheduler.get_anti_spam_shield_status()
    assert shield["system_health"] == "OPTIMAL_PROTECTED"
    assert shield["openrouter_free_rpm_cap"] == 8


def test_agent_schedule_api_endpoints(
    clean_client: TestClient, superadmin_headers: dict[str, str]
):
    """Kiểm thử REST API lịch làm việc và chống spam."""
    # 1. GET /v1/agents/schedule/daily
    res1 = clean_client.get("/v1/agents/schedule/daily", headers=superadmin_headers)
    assert res1.status_code == 200
    data1 = res1.json()
    assert data1["total_shifts"] == 11

    # 2. GET /v1/agents/schedule/anti-spam-status
    res2 = clean_client.get(
        "/v1/agents/schedule/anti-spam-status", headers=superadmin_headers
    )
    assert res2.status_code == 200
    data2 = res2.json()
    assert "active_guards" in data2
