"""Unit & Integration tests for Autonomous Agent Normalization & Self-Healing Engine."""

import asyncio
from unittest.mock import AsyncMock, MagicMock, patch

from app.core.postgres.erp_client import ErpDatabaseClient
from app.modules.agents.application.autonomous_engine_service import (
    AutonomousEngineService,
)


def get_mock_erp_client():
    client = MagicMock(spec=ErpDatabaseClient)
    # Mock session CRUD
    client.create_autonomous_session.return_value = {
        "id": "11111111-2222-3333-4444-555555555555",
        "session_code": "AUTONOMOUS-TEST-001",
        "status": "running",
    }
    client.update_autonomous_session.return_value = {
        "id": "11111111-2222-3333-4444-555555555555",
        "session_code": "AUTONOMOUS-TEST-001",
        "status": "completed",
        "data_quality_index": 95.5,
        "total_records_healed": 3,
    }
    client.list_autonomous_sessions.return_value = [
        {
            "id": "11111111-2222-3333-4444-555555555555",
            "session_code": "AUTONOMOUS-TEST-001",
            "status": "completed",
            "data_quality_index": 95.5,
        }
    ]
    client.get_autonomous_session.return_value = {
        "id": "11111111-2222-3333-4444-555555555555",
        "session_code": "AUTONOMOUS-TEST-001",
        "status": "completed",
    }
    client.list_autonomous_healing_logs.return_value = [
        {
            "agent_code": "thao",
            "table_name": "documents",
            "action_type": "normalize_metadata",
            "reason": "Làm sạch trích yếu",
        }
    ]
    client.get_autonomous_overview.return_value = {
        "total_sessions": 1,
        "total_healed_records": 3,
        "avg_dqi": 95.5,
        "last_sweep_at": "2026-08-24T01:00:00",
    }
    return client


def test_heal_documents_module():
    """Kiểm thử phân hệ tự chuẩn hóa văn bản của AI Thảo & Thủy."""
    mock_erp = get_mock_erp_client()
    service = AutonomousEngineService(erp_client=mock_erp)

    mock_docs = [
        {
            "id": "doc-01",
            "document_code": "TB-01",
            "document_title": "Thông báo mời thầu (Bảo mật Zero-Trust) <!-- tag -->",
            "document_type": "TB",
            "signature_status": "fully_executed",
            "audit_readiness_score": 50,  # Wrong score, should be 100
            "verification_status": "processing",
            "partner_tax_code": "0202111150",
            "project_id": "proj-01",
        },
        {
            "id": "doc-02",
            "document_code": "CV-02",
            "document_title": "Công văn trao đổi",
            "document_type": "CV",
            "signature_status": "draft",
            "audit_readiness_score": 50,
            "verification_status": "pending_review",
            "partner_tax_code": "INVALID_TAX",  # Invalid format
            "project_id": None,
            "business_pillar_category": None,
        },
    ]

    mock_conn = MagicMock()
    mock_cursor = MagicMock()
    mock_cursor.fetchall.return_value = mock_docs
    mock_conn.__enter__.return_value = mock_conn
    mock_conn.cursor.return_value.__enter__.return_value = mock_cursor
    mock_erp.get_connection.return_value = mock_conn

    res = service.heal_documents_module("session-01")

    assert res["agent"] == "thao"
    assert res["scanned"] == 2
    assert res["healed"] >= 1
    # Check that invalid tax code triggered a warning finding
    assert any("INVALID_TAX" in f["message"] for f in res["findings"])


def test_heal_invoices_module_pillars():
    """Kiểm thử phân loại tự động 4 Trụ Cột và kiểm tra số học VAT của AI Nam."""
    mock_erp = get_mock_erp_client()
    service = AutonomousEngineService(erp_client=mock_erp)

    mock_invs = [
        {
            "id": "inv-01",
            "invoice_number": "HD-001",
            "seller_tax_code": "0200149705",  # Thoát nước HP -> Pillar 2
            "seller_name": "Công ty TNHH MTV Thoát Nước Hải Phòng",
            "total_amount_pretax": "100000000.0000",
            "vat_amount": "8000000.0000",
            "total_amount_final": "108000000.0000",
            "business_pillar_category": None,
        },
        {
            "id": "inv-02",
            "invoice_number": "HD-002",
            "seller_tax_code": "0201889988",  # Loan Khải -> Pillar 3
            "seller_name": "Công ty Loan Khải",
            "total_amount_pretax": "50000000.0000",
            "vat_amount": "5000000.0000",
            "total_amount_final": "55000000.0000",
            "business_pillar_category": "pillar_1_construction_epc",  # Wrong, should heal to pillar_3
        },
    ]

    mock_conn = MagicMock()
    mock_cursor = MagicMock()
    mock_cursor.fetchall.return_value = mock_invs
    mock_conn.__enter__.return_value = mock_conn
    mock_conn.cursor.return_value.__enter__.return_value = mock_cursor
    mock_erp.get_connection.return_value = mock_conn

    res = service.heal_invoices_module("session-01")
    assert res["agent"] == "nam"
    assert res["scanned"] == 2
    assert res["healed"] >= 1


def test_run_full_autonomous_sweep():
    """Kiểm thử quy trình chạy trọn vẹn phiên tự trị Master Sweep."""
    mock_erp = get_mock_erp_client()
    service = AutonomousEngineService(erp_client=mock_erp)

    # Mock all sub-engines
    service.heal_documents_module = MagicMock(
        return_value={"agent": "thao", "scanned": 10, "healed": 2, "findings": []}
    )
    service.heal_invoices_module = MagicMock(
        return_value={"agent": "nam", "scanned": 15, "healed": 3, "findings": []}
    )
    service.heal_projects_evm_module = MagicMock(
        return_value={"agent": "quynh", "scanned": 5, "healed": 0, "findings": []}
    )
    service.heal_equipment_module = MagicMock(
        return_value={"agent": "hung", "scanned": 8, "healed": 0, "findings": []}
    )

    res = asyncio.run(
        service.run_full_autonomous_sweep(
            session_type="manual_trigger", lead_agent="minh"
        )
    )

    assert res is not None
    assert mock_erp.create_autonomous_session.called
    assert mock_erp.update_autonomous_session.called


def test_api_routes_integration():
    """Kiểm thử API Client gọi các routes tự trị."""
    from fastapi.testclient import TestClient

    from app.main import create_app

    app = create_app()
    headers = {"Authorization": "Bearer dev-test-token"}

    with patch(
        "app.modules.agents.application.autonomous_engine_service.AutonomousEngineService.run_full_autonomous_sweep",
        new_callable=AsyncMock,
    ) as mock_sweep:
        mock_sweep.return_value = {
            "session_code": "AUTONOMOUS-20260824-001",
            "status": "completed",
            "data_quality_index": 98.0,
            "total_records_scanned": 38,
            "total_records_healed": 5,
        }

        client = TestClient(app)

        # 1. Test status
        resp_status = client.get("/v1/autonomous/status", headers=headers)
        assert resp_status.status_code == 200
        assert resp_status.json()["status"] == "active"

        # 2. Test overview
        resp_overview = client.get("/v1/autonomous/overview", headers=headers)
        assert resp_overview.status_code == 200

        # 3. Test list sessions
        resp_list = client.get("/v1/autonomous/sessions", headers=headers)
        assert resp_list.status_code == 200

        # 4. Test run session
        resp_run = client.post(
            "/v1/autonomous/run-session",
            json={"session_type": "manual_trigger", "lead_agent_code": "minh"},
            headers=headers,
        )
        assert resp_run.status_code == 200
        assert resp_run.json()["status"] == "success"
