from __future__ import annotations

from cadis import _rest


def test_perform_lookup_strict_no_bootstrap(monkeypatch):
    calls = {"lookup": 0, "bootstrap": 0}

    def _lookup(lat: float, lon: float):
        calls["lookup"] += 1
        return {
            "execution": {"lookup_status": "failed"},
            "state": {
                "world": {"classification": "country", "iso2": "TW"},
                "dataset": {"status": "missing", "iso2": "TW"},
            },
        }

    monkeypatch.setattr(_rest, "lookup", _lookup)
    monkeypatch.setattr(
        _rest,
        "bootstrap",
        lambda *args, **kwargs: calls.__setitem__("bootstrap", calls["bootstrap"] + 1),
    )

    out = _rest.perform_lookup(25.03, 121.56, mode="strict")
    assert out["execution"]["lookup_status"] == "failed"
    assert calls["lookup"] == 1
    assert calls["bootstrap"] == 0


def test_perform_lookup_lazy_auto_update_bootstrap_and_retry(monkeypatch):
    seq = iter(
        [
            {
                "execution": {"lookup_status": "failed"},
                "state": {
                    "world": {"classification": "country", "iso2": "TW"},
                    "dataset": {"status": "missing", "iso2": "TW"},
                },
            },
            {
                "execution": {"lookup_status": "ok"},
                "state": {
                    "world": {"classification": "country", "iso2": "TW"},
                    "dataset": {"status": "ready", "iso2": "TW"},
                },
                "result": {"country": {"name": "Taiwan"}},
            },
        ]
    )
    calls: list[tuple[str, dict[str, object]]] = []

    monkeypatch.setattr(_rest, "lookup", lambda lat, lon: next(seq))

    def _bootstrap(iso2: str, **kwargs):
        calls.append((iso2, kwargs))
        return {"bootstrap_status": "ready"}

    monkeypatch.setattr(_rest, "bootstrap", _bootstrap)
    monkeypatch.setattr(_rest, "SUPPORTED_ISO2", ["JP", "TW"])

    out = _rest.perform_lookup(25.03, 121.56, mode="lazy", auto_update=True)
    assert out["execution"]["lookup_status"] == "ok"
    assert len(calls) == 1
    assert calls[0][0] == "TW"
    assert calls[0][1]["update_to_latest"] is True


def test_perform_lookup_lazy_unsupported_country_skips_bootstrap(monkeypatch):
    calls = {"bootstrap": 0}
    monkeypatch.setattr(
        _rest,
        "lookup",
        lambda lat, lon: {
            "execution": {"lookup_status": "failed"},
            "state": {
                "world": {"classification": "country", "iso2": "HK"},
                "dataset": {"status": "missing", "iso2": "HK"},
            },
        },
    )
    monkeypatch.setattr(_rest, "SUPPORTED_ISO2", ["JP", "TW"])
    monkeypatch.setattr(
        _rest,
        "bootstrap",
        lambda *args, **kwargs: calls.__setitem__("bootstrap", calls["bootstrap"] + 1),
    )

    out = _rest.perform_lookup(22.26, 114.16, mode="lazy")
    assert out["state"]["world"]["iso2"] == "HK"
    assert calls["bootstrap"] == 0


def test_sanitize_payload_removes_internal_dataset_fields():
    payload = {
        "state": {
            "dataset": {
                "status": "ready",
                "iso2": "TW",
                "dataset_dir": "/root/.cache/cadis/TW/tw.admin/v1.0.3",
            }
        },
        "dataset": {
            "dataset_manifest_url": "https://example.com/m.json",
            "release_manifest_url": "https://example.com/r.json",
            "package_url": "https://example.com/p.tar.gz",
            "package_sha_url": "https://example.com/p.tar.gz.sha256",
            "dataset_version": "v1.0.3",
        },
    }
    out = _rest._sanitize_payload(payload)
    assert "dataset_dir" not in out["state"]["dataset"]
    assert "dataset_manifest_url" not in out["dataset"]
    assert "release_manifest_url" not in out["dataset"]
    assert "package_url" not in out["dataset"]
    assert "package_sha_url" not in out["dataset"]
    assert out["dataset"]["dataset_version"] == "v1.0.3"


def test_public_bootstrap_payload_is_minimal_and_sanitized():
    payload = {
        "engine": "cadis",
        "version": "0.2.0",
        "bootstrap_status": "ready",
        "state": {
            "dataset": {
                "status": "ready",
                "iso2": "TW",
                "dataset_dir": "/root/.cache/cadis/TW/tw.admin/v1.0.3",
            }
        },
        "dataset": {
            "country_iso2": "TW",
            "dataset_id": "tw.admin",
            "dataset_version": "v1.0.3",
            "dataset_manifest_url": "https://example.com/m.json",
            "dataset_dir": "/root/.cache/cadis/TW/tw.admin/v1.0.3",
        },
    }
    out = _rest._public_bootstrap_payload(payload)
    assert set(out.keys()) == {"engine", "version", "bootstrap_status", "state", "dataset"}
    assert "dataset_dir" not in out["state"]["dataset"]
    assert out["dataset"] == {
        "country_iso2": "TW",
        "dataset_id": "tw.admin",
        "dataset_version": "v1.0.3",
    }
