"""Tests for legacy energy-model compatibility helpers."""

import httpx

from dalysdk import DalyClient, LegacyEnergyModel

AUTH_RESPONSE = {
    "result": "success",
    "token": "test-jwt",
}


def _mock_transport(
    responses: dict[str, httpx.Response],
    seen_requests: list[httpx.Request] | None = None,
) -> httpx.MockTransport:
    def handler(request: httpx.Request) -> httpx.Response:
        if seen_requests is not None:
            seen_requests.append(request)
        if request.url.path == "/auth/token":
            return httpx.Response(200, json=AUTH_RESPONSE)
        key = f"{request.method} {request.url.path}"
        return responses.get(key, httpx.Response(404, json={"detail": f"No mock for {key}"}))

    return httpx.MockTransport(handler)


def _make_client(
    responses: dict[str, httpx.Response],
    *,
    seen_requests: list[httpx.Request] | None = None,
) -> DalyClient:
    client = DalyClient(workspace_api_key="wk_test", user_api_key="uk_test")
    client._base_url = "https://mock.dalyenergy.com"
    client._auth._base_url = "https://mock.dalyenergy.com"
    client._http = httpx.Client(
        base_url="https://mock.dalyenergy.com",
        transport=_mock_transport(responses, seen_requests=seen_requests),
    )

    import time

    client._auth._token = "test-jwt-token"
    client._auth._token_expiry = time.time() + 86400
    return client


def test_create_legacy_query_sets_query_params_and_body_fields():
    requests: list[httpx.Request] = []
    client = _make_client(
        {
            "POST /energymodels": httpx.Response(
                202,
                json={"ok": True, "taskDetails": {"taskId": 9}},
            ),
        },
        seen_requests=requests,
    )

    payload = {
        "blocks": [{"name": "A"}, {"name": "B"}],
        "location": {"latitude": 1, "longitude": 2},
    }
    result = client.energy_models.create_legacy_query(
        payload,
        block_results=True,
        block_results_index=1,
        async_mode=True,
    )

    assert result["ok"] is True
    req = requests[-1]
    assert req.url.params.get("blockresults") == "true"
    posted = req.read().decode("utf-8")
    assert '"blockQuery":true' in posted
    assert '"blockQueryIndex":1' in posted
    assert '"name":"B"' in posted
    assert '"name":"A"' in posted
    client.close()


def test_client_run_energy_model_returns_legacy_tuple():
    client = _make_client(
        {
            "POST /energymodels": httpx.Response(202, json={"taskDetails": {"taskId": 9}}),
        }
    )

    success, result = client.run_energy_model(
        {
            "blocks": [{"name": "A"}],
            "location": {"latitude": 1, "longitude": 2},
        },
        block_results=True,
        run_async=True,
    )

    assert success is True
    assert result["taskDetails"]["taskId"] == 9
    client.close()


def test_legacy_energy_model_run_query_uses_legacy_block_controls():
    requests: list[httpx.Request] = []
    client = _make_client(
        {
            "POST /energymodels": httpx.Response(
                202,
                json={"blockTimeSeries": {"0": {"x": [1]}}},
            ),
        },
        seen_requests=requests,
    )

    em = LegacyEnergyModel(
        client,
        epm_input_json={
            "blocks": [{"name": "A"}, {"name": "B"}],
            "location": {"latitude": 1, "longitude": 2},
        },
    )

    result = em.run_query(
        start_date="2024-01-01",
        end_date="2024-01-02",
        block_results=True,
        block_results_index=0,
        run_async=True,
    )

    assert em.epm_query_run_success is True
    assert result["blockTimeSeries"]["0"]["x"] == [1]
    req = requests[-1]
    assert req.url.params.get("blockresults") == "true"
    client.close()
