"""B1-O admission diagnostic: no provider, network, or production writes."""

import json
from types import SimpleNamespace
from unittest.mock import Mock

import pytest

from scripts import diagnose_discovery_admission_13b as diagnostic


@pytest.mark.asyncio
async def test_comparison_uses_real_gate_and_keeps_fresh_and_reused_lifecycles(monkeypatch):
    clients, calls = [], []

    class FakeRedis:
        def __init__(self):
            self.connection_pool = SimpleNamespace(connection_class=object)
            self.closed = False
            clients.append(self)

        async def ping(self):
            return True

        async def info(self, section):
            assert section == "errorstats"
            return {}

        async def eval(self, script, count, key):
            assert "'INCR'" in script and "'EXPIRE',KEYS[1],120" in script
            assert count == 1 and key.startswith("project-intake:budget:")
            assert not self.closed
            calls.append(self)
            return 1

        async def aclose(self):
            self.closed = True

    settings = SimpleNamespace(redis_url="redis://test", project_intake_calls_per_minute=60)
    monkeypatch.setattr(diagnostic, "get_settings", lambda: settings)
    monkeypatch.setattr(diagnostic.Redis, "from_url", lambda *a, **kw: FakeRedis())
    output = Mock()
    output.exists.return_value = False
    output.stem = "13b_b1_admission_prod_host_01"
    await diagnostic.diagnose(2, output)
    receipt = json.loads(output.write_text.call_args.args[0])
    assert len(clients) == 3  # one persistent, two fresh
    assert all(client.closed for client in clients)
    assert len(calls) == 4 and calls.count(clients[0]) == 2
    assert receipt["environment"] == "local"
    assert receipt["provider_calls"] == 0
    assert receipt["policy_changed"] is False
    assert receipt["measurement_kind"] == "production_admission_gated"
    assert receipt["run_id"] == "13b_b1_admission_prod_host_01"
    assert len(receipt["rows"]) == 4
    assert all(row["error_type"] is None for row in receipt["rows"])


@pytest.mark.asyncio
async def test_diagnostic_refuses_overwrite(monkeypatch):
    monkeypatch.setattr(diagnostic, "preflight", lambda: {})
    output = Mock()
    output.exists.return_value = True
    with pytest.raises(ValueError, match="new diagnostic"):
        await diagnostic.diagnose(1, output)
    output.write_text.assert_not_called()


def test_preflight_fails_if_admission_policy_differs(monkeypatch):
    monkeypatch.setattr(
        diagnostic,
        "get_settings",
        lambda: SimpleNamespace(redis_url="redis://test", project_intake_calls_per_minute=30),
    )
    with pytest.raises(ValueError, match="60/min"):
        diagnostic.preflight()
