"""`staging-refresh.py`'s guard counts the ledger and fails hard when it cannot count (Stream
K2; spec test 21). What it cost before: a dropped `overrides` table would have made the refusal
silently stop firing, and a refresh would have discarded every decision on staging."""
from __future__ import annotations

import importlib.util
import pathlib
import subprocess
import sys

import pytest

SCRIPT = pathlib.Path(__file__).resolve().parents[2] / "main" / "scripts" / "staging-refresh.py"


def load():
    spec = importlib.util.spec_from_file_location("staging_refresh", SCRIPT)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


def test_the_guard_names_the_ledger_and_fails_hard_when_the_count_errors(tmp_path, monkeypatch):
    script = load()
    dump = tmp_path / "prod.dump"; dump.write_bytes(b"PGDMP" + b"\x00" * 16)
    calls = []

    def fake_sh(cmd, *, stdin=None, capture=False, cwd=None, check=True):
        calls.append(cmd)
        if "staging-refresh export" in cmd:
            return subprocess.CompletedProcess(cmd, 0, stdout='{"schema_version": "x", "counts": {"threads": 1}, "tables": {}}', stderr="")
        if "select 'decisions'" in cmd:
            return subprocess.CompletedProcess(cmd, 1, stdout="", stderr='ERROR:  relation "decisions" does not exist')
        return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="")

    monkeypatch.setattr(script, "sh", fake_sh)
    monkeypatch.setattr(script, "ROOT", tmp_path)
    monkeypatch.setattr(script, "REFRESH_DIR", tmp_path / "refresh")
    monkeypatch.setattr(sys, "argv", ["staging-refresh.py", "--from", str(dump), "--db-container", "dfp-devdb"])
    with pytest.raises(SystemExit) as stopped:
        script.main()
    assert stopped.value.code == 4
    guard = next(c for c in calls if "select 'decisions'" in c)
    assert "-v ON_ERROR_STOP=1" in guard and "from proposals" in guard and "overrides" not in guard
    assert not any("drop schema" in c for c in calls), "nothing was dropped"
