"""Tests for scripts/collect_working_leo_production_preflight.py."""

from __future__ import annotations

import argparse
import sys
from pathlib import Path

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

import collect_working_leo_production_preflight as preflight  # noqa: E402


def _args(tmp_path: Path, *, execute: bool = False, transport: str = "ssh") -> argparse.Namespace:
    return argparse.Namespace(
        report_dir=REPO_ROOT / preflight.REPO_REPORT_DIR,
        out=tmp_path / "preflight.json",
        markdown_out=tmp_path / "preflight.md",
        execute=execute,
        transport=transport,
        ssh_target="root@example.invalid",
        ssh_key=tmp_path / "ssh-key",
        connect_timeout=3,
        timeout=10,
        container="teleo-pg",
        db_user="postgres",
        db="teleo",
    )


def test_current_preflight_files_validate_without_execution(tmp_path: Path):
    report = preflight.collect_preflight(_args(tmp_path))

    assert report["status"] == "pass"
    assert report["execute_requested"] is False
    assert report["mutates_production_db"] is False
    assert report["applies_production_packet"] is False
    assert report["production_apply_executed"] is False
    assert report["readonly_transaction_wrapper"] is True
    assert report["preflight_count"] == 5
    assert report["passes"] == 5
    assert all(item["static_readonly_ok"] for item in report["results"])
    assert all(item["executed"] is False for item in report["results"])


def test_forbidden_tokens_reject_mutating_sql():
    sql = """
    -- update in a comment is ignored
    select 'delete from public.claims' as harmless_string;
    update public.claims set status = 'applied';
    """

    assert preflight.forbidden_tokens(sql) == ["update"]


def test_execute_mode_wraps_sql_readonly_and_uses_ssh(monkeypatch, tmp_path: Path):
    calls = []

    class Completed:
        returncode = 0
        stdout = "ok\n"
        stderr = ""

    def fake_run(command, *, input, text, capture_output, timeout, check):
        calls.append(
            {
                "command": command,
                "input": input,
                "text": text,
                "capture_output": capture_output,
                "timeout": timeout,
                "check": check,
            }
        )
        return Completed()

    monkeypatch.setattr(preflight.subprocess, "run", fake_run)

    report = preflight.collect_preflight(_args(tmp_path, execute=True))

    assert report["status"] == "pass"
    assert report["execute_requested"] is True
    assert report["passes"] == 5
    assert len(calls) == 5
    for call in calls:
        assert call["command"][0] == "ssh"
        assert "docker exec -i teleo-pg psql" in call["command"][-1]
        assert call["input"].startswith("\\set ON_ERROR_STOP on\nbegin transaction read only;\n")
        assert call["input"].rstrip().endswith("commit;")


def test_execute_mode_can_run_local_docker_on_vps(monkeypatch, tmp_path: Path):
    calls = []

    class Completed:
        returncode = 0
        stdout = "ok\n"
        stderr = ""

    def fake_run(command, *, input, text, capture_output, timeout, check):
        calls.append({"command": command, "input": input})
        return Completed()

    monkeypatch.setattr(preflight.subprocess, "run", fake_run)

    report = preflight.collect_preflight(_args(tmp_path, execute=True, transport="local-docker"))

    assert report["status"] == "pass"
    assert report["transport"] == "local-docker"
    assert len(calls) == 5
    for call in calls:
        assert call["command"][:3] == ["docker", "exec", "-i"]
        assert "ssh" not in call["command"]
        assert call["input"].startswith("\\set ON_ERROR_STOP on\nbegin transaction read only;\n")


def test_markdown_preserves_claim_ceiling(tmp_path: Path):
    report = preflight.collect_preflight(_args(tmp_path))
    out = tmp_path / "preflight.md"

    preflight.write_markdown(out, report)

    text = out.read_text()
    assert "Working Leo Production Preflight" in text
    assert "Mutates production DB: `False`" in text
    assert "Production apply executed: `False`" in text
    assert "does not authorize production apply" in text
