import pytest

from app.core.postgres.erp_client import ErpDatabaseClient

@pytest.fixture(autouse=True)
def cleanup_test_takeoffs():
    """Rule 12 Teardown: Thu dọn sạch sẽ toàn bộ dữ liệu kiểm thử trong DB sau khi test kết thúc."""
    yield
    try:
        db = ErpDatabaseClient()
        takeoffs = db.list_drawing_takeoffs()
        for t in takeoffs:
            title = (
                t.get("filename")
                or t.get("drawing_name")
                or t.get("drawing_title")
                or ""
            )
            title_upper = title.upper()
            if (
                "TEST" in title_upper
                or "SAMPLE" in title_upper
                or "API_CAD" in title_upper
                or "DWG_" in title_upper
                or "FAST_UPLOAD" in title_upper
                or "DIRECT_CONVERT" in title_upper
                or "DRAWING_DEL" in title_upper
                or "NEW_UNKNOWN" in title_upper
                or "PRELIMINARY" in title_upper
                or "GEMINI_" in title_upper
                or "BATCH_DRAWING" in title_upper
                or "NVH_DAI_THANG" in title_upper
                or "BAN_VE_THI_CONG" in title_upper
            ):
                db.delete_drawing_takeoff(t["id"])
                
        # Clean up test projects
        with db.get_connection() as conn, conn.cursor() as cur:
            cur.execute("DELETE FROM projects WHERE project_code = %s OR project_name LIKE %s", ("DA-SONGLO-2026", "%Nhà điều hành KCN Sông Lô%"))
            conn.commit()

        from pathlib import Path
        drawings_dir = Path("app/static/drawings")
        uploads_dir = Path("app/static/uploads")
        if drawings_dir.exists():
            for p in drawings_dir.iterdir():
                p_upper = p.name.upper()
                if any(x in p_upper for x in ["TEST", "SAMPLE", "API_CAD", "DWG_", "FAST_UPLOAD", "DIRECT_CONVERT", "DRAWING_DEL", "NEW_UNKNOWN", "PRELIMINARY", "GEMINI_", "BATCH_DRAWING", "NVH_DAI_THANG", "BAN_VE_THI_CONG"]):
                    try:
                        p.unlink()
                    except Exception:
                        pass
        if uploads_dir.exists():
            for p in uploads_dir.iterdir():
                p_upper = p.name.upper()
                if any(x in p_upper for x in ["TEST", "SAMPLE", "API_CAD", "DWG_", "FAST_UPLOAD", "DIRECT_CONVERT", "DRAWING_DEL", "NEW_UNKNOWN", "PRELIMINARY", "GEMINI_", "BATCH_DRAWING", "NVH_DAI_THANG", "BAN_VE_THI_CONG"]):
                    try:
                        p.unlink()
                    except Exception:
                        pass
    except Exception as e:
        print(f"Teardown error: {e}")

@pytest.fixture(scope="session")
def vcr_config():
    """Global configuration for pytest-recording (vcrpy)."""
    return {
        "filter_headers": ["authorization", "x-api-key"],
        "ignore_localhost": True,
        "record_mode": "once",
        "cassette_library_dir": "tests/cassettes",
    }

def pytest_configure(config):
    config.addinivalue_line(
        "markers", "vcr: Mark test to record/replay network interactions with VCR"
    )

def pytest_collection_modifyitems(config, items):
    """Safely apply VCR cache only when the recording plugin is active and targeted."""
    if config.pluginmanager.hasplugin("recording"):
        for item in items:
            if item.get_closest_marker("vcr_cassette"):
                item.add_marker(pytest.mark.vcr)
