from __future__ import annotations

import os
import stat
import subprocess
from pathlib import Path


ROOT = Path(__file__).resolve().parents[3]
RECOVERY = ROOT / "scripts/reboot-recovery/recover-110-control-path-and-harbor-local.sh"


def test_recover_110_orchestrator_contracts() -> None:
    text = RECOVERY.read_text(encoding="utf-8")

    assert "--check" in text
    assert "--apply-ssh-metadata" in text
    assert "--apply-ssh-control-path" in text
    assert "--repair-harbor-once" in text
    assert "--apply-all" in text
    assert "operation_boundary_secret_value_read=false" in text
    assert "operation_boundary_runner_token_read=false" in text
    assert "operation_boundary_raw_runner_registration_read=false" in text
    assert "operation_boundary_authorized_keys_content_printed=false" in text
    assert "operation_boundary_ssh_key_material_created=false" in text
    assert "ssh_publickey_auth_stall_recovery_supported=true" in text
    assert "ssh_control_path_apply_alias_supported=true" in text
    assert "operation_boundary_host_reboot_performed=false" in text
    assert "operation_boundary_docker_daemon_restart_performed=false" in text
    assert "repair-110-ssh-publickey-auth-local.sh" in text
    assert "harbor-watchdog.sh" in text
    assert "check-awoooi-110-controlled-cd-lane-readiness.sh" in text
    assert "cat \"$home_dir/.ssh/authorized_keys\"" not in text
    assert "cat \"$CD_LANE_DRAIN_DIR/data/.runner\"" not in text

    forbidden = [
        "systemctl restart docker",
        "service docker restart",
        "\nreboot",
        "\nsudo reboot",
        "\nshutdown",
        "\nsudo shutdown",
        "docker system prune",
        "docker volume rm",
    ]
    for pattern in forbidden:
        assert pattern not in text


def test_recover_110_check_uses_fake_helpers_without_writes(tmp_path: Path) -> None:
    ssh_helper = tmp_path / "ssh-helper.sh"
    harbor_helper = tmp_path / "harbor-helper.sh"
    lane_helper = tmp_path / "lane-helper.sh"
    ssh_helper.write_text(
        "#!/usr/bin/env bash\n"
        "echo SSH_HELPER_MODE=$1\n"
        "echo SSH_METADATA_WRITE=false\n",
        encoding="utf-8",
    )
    harbor_helper.write_text(
        "#!/usr/bin/env bash\n"
        "echo HARBOR_HELPER_MODE=$1\n"
        "echo HARBOR_RUNTIME_WRITE=false\n",
        encoding="utf-8",
    )
    lane_helper.write_text(
        "#!/usr/bin/env bash\n"
        "echo LANE_VERIFIER_MODE=check\n"
        "echo LANE_VERIFIER_REGISTRATION_CONTENT_READ=false\n",
        encoding="utf-8",
    )
    for helper in (ssh_helper, harbor_helper, lane_helper):
        helper.chmod(helper.stat().st_mode | stat.S_IXUSR)

    env = {
        **os.environ,
        "ALLOW_NON_110": "1",
        "AWOOOI_110_SSH_REPAIR_SCRIPT": str(ssh_helper),
        "AWOOOI_HARBOR_WATCHDOG_SCRIPT": str(harbor_helper),
        "AWOOOI_110_CONTROLLED_LANE_VERIFIER_SCRIPT": str(lane_helper),
    }
    result = subprocess.run(
        ["bash", str(RECOVERY), "--check"],
        check=False,
        env=env,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
    )

    assert result.returncode == 0, result.stdout + result.stderr
    assert "AWOOOI_110_CONTROL_PATH_AND_HARBOR_LOCAL_RECOVERY mode=check" in result.stdout
    assert "requested_mode=--check" in result.stdout
    assert "SSH_HELPER_MODE=--check" in result.stdout
    assert "HARBOR_HELPER_MODE=--check" in result.stdout
    assert "LANE_VERIFIER_MODE=check" in result.stdout
    assert "SSH_METADATA_WRITE=false" in result.stdout
    assert "HARBOR_RUNTIME_WRITE=false" in result.stdout
    assert "LANE_VERIFIER_REGISTRATION_CONTENT_READ=false" in result.stdout
    assert "operation_boundary_secret_value_read=false" in result.stdout
    assert "operation_boundary_raw_runner_registration_read=false" in result.stdout


def test_recover_110_accepts_ai_loop_apply_ssh_control_path_alias(
    tmp_path: Path,
) -> None:
    ssh_helper = tmp_path / "ssh-helper.sh"
    harbor_helper = tmp_path / "harbor-helper.sh"
    lane_helper = tmp_path / "lane-helper.sh"
    ssh_helper.write_text(
        "#!/usr/bin/env bash\n"
        "echo SSH_HELPER_MODE=$1\n"
        "echo SSH_METADATA_WRITE=$([ \"$1\" = \"--apply\" ] && echo true || echo false)\n",
        encoding="utf-8",
    )
    harbor_helper.write_text(
        "#!/usr/bin/env bash\n"
        "echo HARBOR_HELPER_SHOULD_NOT_RUN=$1\n"
        "exit 70\n",
        encoding="utf-8",
    )
    lane_helper.write_text(
        "#!/usr/bin/env bash\n"
        "echo LANE_HELPER_SHOULD_NOT_RUN=$1\n"
        "exit 71\n",
        encoding="utf-8",
    )
    for helper in (ssh_helper, harbor_helper, lane_helper):
        helper.chmod(helper.stat().st_mode | stat.S_IXUSR)

    env = {
        **os.environ,
        "ALLOW_NON_110": "1",
        "AWOOOI_110_SSH_REPAIR_SCRIPT": str(ssh_helper),
        "AWOOOI_HARBOR_WATCHDOG_SCRIPT": str(harbor_helper),
        "AWOOOI_110_CONTROLLED_LANE_VERIFIER_SCRIPT": str(lane_helper),
    }
    result = subprocess.run(
        ["bash", str(RECOVERY), "--apply-ssh-control-path"],
        check=False,
        env=env,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
    )

    assert result.returncode == 0, result.stdout + result.stderr
    assert (
        "AWOOOI_110_CONTROL_PATH_AND_HARBOR_LOCAL_RECOVERY mode=apply_ssh_metadata"
        in result.stdout
    )
    assert "requested_mode=--apply-ssh-control-path" in result.stdout
    assert "ssh_control_path_apply_alias_supported=true" in result.stdout
    assert "ssh_control_path_apply_canonical_mode=--apply-ssh-metadata" in result.stdout
    assert "SSH_HELPER_MODE=--apply" in result.stdout
    assert "SSH_METADATA_WRITE=true" in result.stdout
    assert "HARBOR_HELPER_SHOULD_NOT_RUN" not in result.stdout
    assert "LANE_HELPER_SHOULD_NOT_RUN" not in result.stdout
    assert "operation_boundary_authorized_keys_content_printed=false" in result.stdout
    assert "operation_boundary_ssh_key_material_created=false" in result.stdout
