from fastapi import FastAPI
from fastapi.testclient import TestClient
from types import SimpleNamespace

from app.api.v1.endpoints import leakage as leakage_endpoint


def _build_client() -> TestClient:
    app = FastAPI()
    app.include_router(leakage_endpoint.router, prefix="/api/v1/leakage")
    app.dependency_overrides[leakage_endpoint.get_current_keycloak_username] = (
        lambda: "tester"
    )
    return TestClient(app)


def test_identify_leakage_success(monkeypatch):
    def fake_run_leakage_identification(**kwargs):
        assert kwargs["network"] == "demo"
        assert kwargs["username"] == "tester"
        return {"rows": [], "area_count": 0}

    monkeypatch.setattr(
        leakage_endpoint, "run_leakage_identification", fake_run_leakage_identification
    )
    client = _build_client()
    response = client.post(
        "/api/v1/leakage/identify/",
        json={
            "network": "demo",
            "scada_start": "2026-01-01T00:00:00+08:00",
            "scada_end": "2026-01-01T01:00:00+08:00",
            "scheme_name": "dma_001",
        },
    )
    assert response.status_code == 200
    assert response.json()["area_count"] == 0


def test_query_leakage_schemes_success(monkeypatch):
    monkeypatch.setattr(
        leakage_endpoint,
        "list_leakage_identify_schemes",
        lambda network, query_date=None: [
            {"scheme_name": "dma_001", "scheme_type": "dma_leak_identification"}
        ],
    )
    client = _build_client()
    response = client.get("/api/v1/leakage/schemes/", params={"network": "demo"})
    assert response.status_code == 200
    assert response.json()[0]["scheme_name"] == "dma_001"


def test_query_leakage_scheme_detail_success(monkeypatch):
    monkeypatch.setattr(
        leakage_endpoint,
        "get_leakage_identify_scheme_detail",
        lambda network, scheme_name: {
            "scheme_name": scheme_name,
            "rows": [{"Area": "1", "LeakageFlow_m3_per_s": 0.1}],
        },
    )
    client = _build_client()
    response = client.get(
        "/api/v1/leakage/schemes/dma_001", params={"network": "demo"}
    )
    assert response.status_code == 200
    assert response.json()["scheme_name"] == "dma_001"
