from __future__ import annotations

from pathlib import Path


ROOT = Path(__file__).resolve().parents[3]
SCRIPT = ROOT / "scripts" / "reboot-recovery" / "188-host-hygiene-maintenance-checklist.sh"
STARTUP_188 = ROOT / "scripts" / "reboot-recovery" / "awoooi-startup.sh"
STARTUP_188_SERVICE = ROOT / "scripts" / "reboot-recovery" / "awoooi-startup.service"
DEPLOY_188 = ROOT / "scripts" / "reboot-recovery" / "deploy-to-188.sh"


def test_188_and_110_default_to_reachable_runtime_identities() -> None:
    text = SCRIPT.read_text(encoding="utf-8")

    assert 'REMOTE_188="${REMOTE_188:-ollama@192.168.0.188}"' in text
    assert 'REMOTE_110="${REMOTE_110:-wooo@192.168.0.110}"' in text


def test_110_self_check_can_run_locally_without_ssh_config_drift() -> None:
    text = SCRIPT.read_text(encoding="utf-8")

    assert "is_local_target()" in text
    assert 'ips="$(local_ip_list)"' in text
    assert 'local_ip_list | grep' not in text
    assert 'bash -lc "$command"' in text
    assert 'SSH_COMMAND_TIMEOUT_SECONDS="${SSH_COMMAND_TIMEOUT_SECONDS:-25}"' in text
    assert "printf -v quoted_command '%q' \"$command\"" in text
    assert '-o ConnectionAttempts=1' in text
    assert '-o ServerAliveInterval=5' in text
    assert '-o ServerAliveCountMax=1' in text
    assert '-o NumberOfPasswordPrompts=0' in text
    assert 'ssh "${ssh_opts[@]}" "$target" \\' in text
    assert "timeout ${SSH_COMMAND_TIMEOUT_SECONDS}s bash -lc ${quoted_command}" in text


def test_188_startup_keeps_clawbot_rebuild_bounded_and_opt_in() -> None:
    text = STARTUP_188.read_text(encoding="utf-8")

    assert 'CLAWBOT_UP_TIMEOUT_SECONDS="${CLAWBOT_UP_TIMEOUT_SECONDS:-90}"' in text
    assert 'CLAWBOT_BUILD_TIMEOUT_SECONDS="${CLAWBOT_BUILD_TIMEOUT_SECONDS:-120}"' in text
    assert 'CLAWBOT_STARTUP_REBUILD_ALLOWED="${CLAWBOT_STARTUP_REBUILD_ALLOWED:-0}"' in text
    assert "run_bounded()" in text
    assert "docker compose build --no-cache" not in text
    assert 'if [ "$CLAWBOT_STARTUP_REBUILD_ALLOWED" = "1" ]; then' in text
    assert "post-reboot SLO" in text


def test_188_startup_unit_timeout_matches_reboot_slo() -> None:
    text = STARTUP_188_SERVICE.read_text(encoding="utf-8")

    assert "TimeoutStartSec=600" in text


def test_188_deploy_helper_does_not_embed_sudo_password() -> None:
    text = DEPLOY_188.read_text(encoding="utf-8")

    assert "sudo -S" not in text
    assert "PASS=" not in text
    assert "PASSWORD" not in text
    assert "sudo -n true" in text
    assert "BLOCKED sudo_password_required_passwordless_sudo_or_tty_required" in text
