"""Platform-path regression tests for the approved-change clone canary."""

from __future__ import annotations

import subprocess
import sys
from pathlib import Path

import pytest

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))
WRAPPER = ROOT / "scripts" / "run_approve_claim_isolated_container_canary.sh"

import apply_proposal as apply  # noqa: E402
import run_approve_claim_clone_canary as canary  # noqa: E402


def test_role_psql_resolves_docker_before_scrubbing_path(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    captured: dict[str, object] = {}

    monkeypatch.setattr(
        canary.shutil,
        "which",
        lambda executable: "/opt/homebrew/bin/docker"
        if executable == "docker"
        else None,
    )

    def fake_run(command: list[str], **kwargs: object) -> subprocess.CompletedProcess[str]:
        captured["command"] = command
        captured["env"] = kwargs["env"]
        return subprocess.CompletedProcess(command, 0, "", "")

    monkeypatch.setattr(canary, "_run", fake_run)

    canary._role_psql(
        "local-postgres",
        "teleo",
        "select 1;",
        role="kb_apply",
        password="test-only-password",
    )

    assert captured["command"][0] == "/opt/homebrew/bin/docker"
    assert captured["env"] == {
        "PGPASSWORD": "test-only-password",
        "PATH": "/usr/bin:/bin:/usr/local/bin",
    }


def test_apply_tool_resolves_docker_before_scrubbing_path(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    captured: dict[str, object] = {}
    monkeypatch.setattr(
        apply.shutil,
        "which",
        lambda executable: "/opt/homebrew/bin/docker"
        if executable == "docker"
        else None,
    )

    def fake_run(command: list[str], **kwargs: object) -> subprocess.CompletedProcess[str]:
        captured["command"] = command
        captured["env"] = kwargs["env"]
        return subprocess.CompletedProcess(command, 0, "ok", "")

    monkeypatch.setattr(apply.subprocess, "run", fake_run)
    args = type(
        "Args",
        (),
        {
            "container": "local-postgres",
            "role": "kb_apply",
            "host": "127.0.0.1",
            "db": "teleo",
        },
    )()

    assert apply.run_psql(args, "select 1;", "test-only-password") == "ok"
    assert captured["command"][0] == "/opt/homebrew/bin/docker"
    assert captured["env"] == {
        "PGPASSWORD": "test-only-password",
        "PATH": "/usr/bin:/bin:/usr/local/bin",
    }


def test_outer_wrapper_enforces_local_source_and_networkless_tmpfs() -> None:
    text = WRAPPER.read_text(encoding="utf-8")

    assert 'source_canary_label" != "working-leo-approved-source"' in text
    assert "--network none" in text
    assert "--tmpfs /var/lib/postgresql/data:rw,nosuid,size=512m" in text
    assert 'CANARY_NETWORK_MODE="$container_network_mode"' in text
    assert 'CANARY_MOUNTS_JSON="$container_mounts_json"' in text
    assert 'data["checks"]["outer_source_tier_enforced"]' in text
    assert 'data["checks"]["outer_container_network_disabled"]' in text
    assert 'data["checks"]["outer_container_has_no_docker_volumes"]' in text
    assert 'source_tier != "live-readonly" or service_observable' in text
