from __future__ import annotations

from pathlib import Path


ROOT = Path(__file__).resolve().parents[3]
COLD_START_CHECK = ROOT / "scripts" / "reboot-recovery" / "full-stack-cold-start-check.sh"
MOMO_SOURCE_PREFLIGHT = (
    ROOT / "scripts" / "reboot-recovery" / "momo-drive-token-source-recovery-preflight.sh"
)
INSTALL_COLD_START = (
    ROOT / "scripts" / "reboot-recovery" / "install-cold-start-monitor-110.sh"
)
STARTUP_110 = ROOT / "scripts" / "reboot-recovery" / "awoooi-startup-110.sh"
RECOVERY_SCORECARD = (
    ROOT / "scripts" / "reboot-recovery" / "full-stack-recovery-scorecard.sh"
)
VERIFY_DEPLOY = ROOT / "scripts" / "reboot-recovery" / "verify-cold-start-monitor-deploy.sh"
REPAIR_STARTUP_STUB = (
    ROOT / "scripts" / "reboot-recovery" / "repair-110-startup-script-stub.sh"
)
FAILCLOSED_ENFORCER = (
    ROOT / "scripts" / "reboot-recovery" / "enforce-110-runner-failclosed.sh"
)
CONTROLLED_CD_LANE_DRAIN_UNIT = ROOT / "ops" / "runner" / "awoooi-cd-lane-drain.service"
SSH_AUTH_DIAGNOSE = (
    ROOT / "scripts" / "reboot-recovery" / "diagnose-110-ssh-publickey-auth.sh"
)
SSH_AUTH_REPAIR = (
    ROOT / "scripts" / "reboot-recovery" / "repair-110-ssh-publickey-auth-local.sh"
)


def test_full_stack_cold_start_check_bounds_ssh_probes() -> None:
    text = COLD_START_CHECK.read_text(encoding="utf-8")

    assert 'SSH_COMMAND_TIMEOUT_SECONDS="${SSH_COMMAND_TIMEOUT_SECONDS:-45}"' in text
    assert 'SSH_110_CHECK_ATTEMPTS="${SSH_110_CHECK_ATTEMPTS:-4}"' in text
    assert 'SSH_110_CHECK_SLEEP_SECONDS="${SSH_110_CHECK_SLEEP_SECONDS:-5}"' in text
    assert "-o ConnectionAttempts=1" in text
    assert "-o ServerAliveInterval=5" in text
    assert "-o ServerAliveCountMax=1" in text
    assert "timeout ${SSH_COMMAND_TIMEOUT_SECONDS}s bash -lc" in text
    assert "host_cmd_retry()" in text
    assert "SSH_RETRY_RECOVERED user_host=$user_host attempt=$attempt/$attempts" in text
    assert '"$SSH_110_CHECK_ATTEMPTS" "$SSH_110_CHECK_SLEEP_SECONDS"' in text
    assert text.count('host_cmd_retry "wooo@192.168.0.110"') >= 2
    assert "printf -v quoted_cmd '%q' \"$cmd\"" in text
    assert (
        'MOMO_SOURCE_PREFLIGHT_SCRIPT="${MOMO_SOURCE_PREFLIGHT_SCRIPT:-$SCRIPT_DIR/momo-drive-token-source-recovery-preflight.sh}"'
        in text
    )
    assert '"$MOMO_SOURCE_PREFLIGHT_SCRIPT"' in text
    assert 'timeout 3 systemctl "$@"' in text
    assert "SSH_110_BLOCKER remote_control_channel_unavailable" in text
    assert "SSH_110_NEXT_ACTION local_console_run_recover_110_control_path_and_harbor_local_check" in text
    assert "SSH_110_RECOVERY_PACKAGE_EXPECTED /usr/local/bin/recover-110-control-path-and-harbor-local.sh" in text
    assert "SSH_110_RECOVERY_PACKAGE_BLOCKER package_presence_not_verifiable_while_remote_control_channel_unavailable" in text
    assert "SSH_110_RECOVERY_PACKAGE_NEXT_ACTION verify_or_preinstall_local_recovery_package_from_console_before_harbor_repair_retry" in text


def test_cold_start_momo_current_month_handles_no_new_source_without_false_warn() -> None:
    text = COLD_START_CHECK.read_text(encoding="utf-8")

    assert "momo_latest_import_clean" in text
    assert "momo_source_stale_only" in text
    assert "MOMO_SOURCE_ABSENT_WITHOUT_NEWER_DRIVE" in text
    assert "Drive has no newer source than last clean import" in text
    assert "momo daily sales source gate has no newer Drive candidate" in text
    assert "product data freshness is pending source arrival" in text
    assert "a[1] == 0 && a[2] == 0" in text


def test_momo_source_preflight_emits_machine_readable_no_new_source_evidence() -> None:
    text = MOMO_SOURCE_PREFLIGHT.read_text(encoding="utf-8")

    assert "MOMO_LATEST_IMPORT_CLEAN" in text
    assert "MOMO_SOURCE_ABSENT_WITHOUT_NEWER_DRIVE" in text
    assert "source_absent_without_newer_drive=1" in text


def test_cold_start_110_backup_splits_current_freshness_from_old_aggregate_failure() -> None:
    text = COLD_START_CHECK.read_text(encoding="utf-8")

    assert "critical config gaps" in text
    assert "current component freshness is clean" in text
    assert "split($6,a,\"=\"); exit !(a[2] > 0)" in text
    assert "split($7,e,\"=\"); exit !((a[2]+b[2]+c[2]+e[2]) == 0)" in text


def test_recovery_scorecard_bounds_offsite_evidence_ssh() -> None:
    text = RECOVERY_SCORECARD.read_text(encoding="utf-8")

    assert 'REMOTE_COMMAND_TIMEOUT_SECONDS="${REMOTE_COMMAND_TIMEOUT_SECONDS:-45}"' in text
    assert "-o ConnectionAttempts=1" in text
    assert "-o ServerAliveInterval=5" in text
    assert "-o ServerAliveCountMax=1" in text
    assert "remote_110_read()" in text
    assert "timeout ${REMOTE_COMMAND_TIMEOUT_SECONDS}s bash -lc" in text
    assert "offsite-escrow-evidence-report.sh --no-color" in text
    assert "classify_readback_blocker()" in text
    assert "CORE_COLD_START_DEPLOY_PARITY_BLOCKER" in text
    assert "CORE_REGISTRY_HTTPS_CODE" in text
    assert "CORE_REGISTRY_HTTP_CODE" in text
    assert "CORE_REGISTRY_READY" in text
    assert "CORE_REGISTRY_BLOCKER" in text
    assert "registry_5000_unreachable_or_not_ready" in text
    assert "DR_OFFSITE_EVIDENCE_READBACK" in text
    assert "DR_OFFSITE_EVIDENCE_BLOCKER" in text
    assert "ssh_control_channel_timeout" in text


def test_full_stack_cold_start_check_tracks_registry_and_image_pull_blockers() -> None:
    text = COLD_START_CHECK.read_text(encoding="utf-8")

    assert "REGISTRY_EXTERNAL_HTTPS_CODE" in text
    assert "REGISTRY_EXTERNAL_HTTP_CODE" in text
    assert "110 registry external /v2 not reachable" in text
    assert "IMAGE_PULL_BLOCKED" in text
    assert "IMAGE_PULL_REASONS" in text
    assert "REGISTRY_PULL_REFUSED_EVENTS" in text
    assert "K3s AWOOOI image pull blocked" in text
    assert "K3s registry pull refused by 110:5000" in text


def test_startup_110_quarantines_corrupt_docker_container_metadata() -> None:
    text = STARTUP_110.read_text(encoding="utf-8")

    assert "AWOOOI_DOCKER_START_TIMEOUT_SECONDS" in text
    assert "quarantine_corrupt_docker_container_metadata()" in text
    assert "DOCKER_CORRUPT_METADATA_QUARANTINED_COUNT" in text
    assert "failed to load container|invalid character|json: cannot unmarshal|unexpected EOF" in text
    assert 'mv "$src" "$qdir/$id"' in text
    assert "systemctl kill --kill-who=main --signal=TERM docker.service" in text
    assert 'run_bounded "$DOCKER_START_TIMEOUT_SECONDS" systemctl start docker.socket docker.service' in text


def test_startup_110_repairs_ssh_control_path_metadata_before_docker() -> None:
    text = STARTUP_110.read_text(encoding="utf-8")

    repair_fn = text.index("repair_ssh_control_path_metadata()")
    repair_call = text.index("repair_ssh_control_path_metadata", repair_fn + 1)
    docker_step = text.index('log "[1/5] 檢查 Docker..."')

    assert repair_fn < repair_call < docker_step
    assert 'AWOOOI_110_SSH_REPAIR_SCRIPT:-/usr/local/bin/repair-110-ssh-publickey-auth-local.sh' in text
    assert 'AWOOOI_110_SSH_REPAIR_USER:-wooo' in text
    assert 'AWOOOI_110_SSH_RELOAD_AFTER_REPAIR:-0' in text
    assert 'TARGET_USER="$target_user" RELOAD_SSH="$reload_ssh" "$script" --apply' in text
    assert "SSH control path metadata guard completed" in text
    assert "cat \"$home_dir/.ssh/authorized_keys\"" not in text
    assert "cat ~/.ssh/authorized_keys" not in text
    assert "ssh-keygen" not in text
    assert "ssh-copy-id" not in text


def test_startup_110_opens_only_controlled_cd_lane_after_guardrails() -> None:
    text = STARTUP_110.read_text(encoding="utf-8")

    assert 'START_CONTROLLED_CD_LANE="${AWOOOI_START_CONTROLLED_CD_LANE:-1}"' in text
    assert "cd_lane_root_restore_sources_left()" in text
    assert 'CD_LANE_ROOT_RESTORE_LEFT="$(cd_lane_root_restore_sources_left)"' in text
    assert 'START_CD_LANE_ALLOWED=1' in text
    assert 'install_controlled_cd_lane_drain_unit' in text
    assert 'ConditionPathExists=${CD_LANE_DRAIN_DIR}/data/.runner' in text
    assert 'systemctl unmask "$CD_LANE_DRAIN_SERVICE"' in text
    assert 'systemctl enable --now "$CD_LANE_DRAIN_SERVICE"' in text
    assert 'ensure_controlled_cd_lane_open' in text
    assert 'if [ "$START_CD_LANE_ALLOWED" = "1" ] && [ "$binary" = "$CD_LANE_DRAIN_BINARY" ]; then' in text
    assert 'systemctl enable --now "$RUNNER_SERVICE"' in text
    assert "legacy runner 仍維持 fail-closed" in text
    assert "controlled cd-lane remains closed because guardrails failed or AWOOOI_START_CONTROLLED_CD_LANE=0" in text


def test_cold_start_deploy_parity_verifier_bounds_ssh_readback() -> None:
    text = VERIFY_DEPLOY.read_text(encoding="utf-8")

    assert 'REMOTE_COMMAND_TIMEOUT_SECONDS="${REMOTE_COMMAND_TIMEOUT_SECONDS:-45}"' in text
    assert "-o ConnectionAttempts=1" in text
    assert "-o ServerAliveInterval=5" in text
    assert "-o ServerAliveCountMax=1" in text
    assert "remote_read()" in text
    assert "timeout ${REMOTE_COMMAND_TIMEOUT_SECONDS}s bash -lc" in text
    assert 'remote_read "sha256sum' in text
    assert 'if remote_read "grep -Fq' in text
    assert "momo-drive-token-source-recovery-preflight.sh" in text


def test_cold_start_monitor_installer_deploys_source_preflight_dependency() -> None:
    text = INSTALL_COLD_START.read_text(encoding="utf-8")

    assert "-o ConnectionAttempts=1" in text
    assert "-o ServerAliveInterval=5" in text
    assert "-o ServerAliveCountMax=1" in text
    assert 'ssh "${SSH_OPTS[@]}"' in text
    assert 'scp "${SSH_OPTS[@]}"' in text
    assert 'BACKUP_SUFFIX="${BACKUP_SUFFIX:-before-cold-start-monitor-$(date +%Y%m%d-%H%M%S)}"' in text
    assert "cp -p" in text
    assert "$BACKUP_SUFFIX" in text
    assert 'MOMO_PREFLIGHT_SCRIPT="$SCRIPT_DIR/momo-drive-token-source-recovery-preflight.sh"' in text
    assert 'scp "${SSH_OPTS[@]}" "$MOMO_PREFLIGHT_SCRIPT"' in text
    assert "momo-drive-token-source-recovery-preflight.sh" in text


def test_repair_110_startup_stub_is_bounded_and_does_not_start_by_default() -> None:
    text = REPAIR_STARTUP_STUB.read_text(encoding="utf-8")

    assert 'MODE="verify"' in text
    assert 'START_SERVICE=0' in text
    assert "--start-service" in text
    assert "-o ConnectionAttempts=1" in text
    assert "-o ServerAliveInterval=5" in text
    assert "-o ServerAliveCountMax=1" in text
    assert "remote_is_runner_failclosed_stub" in text
    assert 'sudo -n chattr -i "\\$REMOTE_PATH"' in text
    assert 'sudo -n install -o root -g root -m 0755 "\\$REMOTE_TMP" "\\$REMOTE_PATH"' in text
    assert "sudo -n systemctl reset-failed awoooi-startup-110.service" in text
    assert "docker ps" not in text
    assert "docker compose up -d" not in text
    assert "systemctl restart docker" not in text
    assert "systemctl reload nginx" not in text
    assert "kubectl" not in text
    assert "cat ~/.ssh" not in text
    assert "cat .env" not in text


def test_runner_failclosed_enforcer_does_not_seal_live_startup_recovery_script() -> None:
    text = FAILCLOSED_ENFORCER.read_text(encoding="utf-8")

    assert 'write_failclosed_stub "/usr/local/bin/awoooi-startup-110.sh"' not in text
    assert "-name 'awoooi-startup-110.sh' \\" not in text
    assert "awoooi-startup-110.sh.*controlled*" in text


def test_runner_failclosed_enforcer_preserves_controlled_drain_staging_or_guarded_active() -> None:
    text = FAILCLOSED_ENFORCER.read_text(encoding="utf-8")

    assert "controlled_drain_staging_allowed()" in text
    assert "controlled_drain_active_allowed()" in text
    assert "controlled_drain_preserve_allowed()" in text
    assert "controlled_drain_config_safe" in text
    assert "controlled_drain_binary_safe" in text
    assert "controlled_drain_unit_safe" in text
    assert "controlled_drain_service_inactive" in text
    assert "controlled_drain_registration_present" in text
    assert "controlled_drain_service_active_guarded" in text
    assert 'lane_process_count_ok \\' in text
    assert "bounded_chattr_recursive_clear()" in text
    assert "as_root timeout 5s chattr -R -i" in text
    assert "awoooi-host:host" in text
    assert (
        "awoooi-ubuntu:docker://192.168.0.110:5000/awoooi/ci-runner:act-22.04"
        in text
    )
    assert "ubuntu-latest|ubuntu-*|self-hosted|stockplatform*|stock-platform*|headless*|playwright*)" in text
    assert 'grep -Fq -- "ConditionPathExists=$CONTROLLED_DRAIN_REGISTRATION"' in text
    assert 'grep -Eq \'^[[:space:]]*CPUAccounting=true\'' in text
    assert 'grep -Eq \'^[[:space:]]*MemoryAccounting=true\'' in text
    assert 'grep -Eq \'^[[:space:]]*TasksAccounting=true\'' in text
    assert '[ "$unitfile" != "enabled" ] || return 1' in text
    assert 'if [ "$unit" = "$CONTROLLED_DRAIN_UNIT" ] && controlled_drain_preserve_allowed; then' in text
    assert 'if [ "$path" = "$CONTROLLED_DRAIN_BINARY" ] && controlled_drain_preserve_allowed; then' in text
    assert 'if [ "$lane_dir" = "$CONTROLLED_DRAIN_DIR" ] && controlled_drain_preserve_allowed; then' in text
    assert "CONTROLLED_DRAIN_STAGING_ALLOWED=" in text
    assert "CONTROLLED_DRAIN_ACTIVE_ALLOWED=" in text
    assert "CONTROLLED_DRAIN_PRESERVE_ALLOWED=" in text


def test_controlled_cd_lane_unit_source_has_required_accounting_guardrails() -> None:
    text = CONTROLLED_CD_LANE_DRAIN_UNIT.read_text(encoding="utf-8")

    assert "ConditionPathExists=/home/wooo/awoooi-cd-lane-drain/data/.runner" in text
    assert "CPUAccounting=true" in text
    assert "CPUQuota=250%" in text
    assert "MemoryAccounting=true" in text
    assert "MemoryHigh=8G" in text
    assert "MemoryMax=12G" in text
    assert "TasksAccounting=true" in text
    assert "TasksMax=512" in text
    assert "IOAccounting=true" in text
    assert "IOWeight=100" in text
    assert "NoNewPrivileges=true" in text


def test_110_ssh_publickey_auth_diagnosis_is_bounded_and_read_only() -> None:
    text = SSH_AUTH_DIAGNOSE.read_text(encoding="utf-8")

    assert "PasswordAuthentication=no" in text
    assert "PubkeyAuthentication=no" in text
    assert "NumberOfPasswordPrompts=0" in text
    assert "SSH_COMMAND_PATH_TIMEOUT_SECONDS" in text
    assert "COMMAND_PATH_USER" in text
    assert "SSH_COMMAND_PATH user=%s rc=%s classification=%s" in text
    assert "command_path_ready" in text
    assert "AWOOOI_110_COMMAND_PATH_READY=1" in text
    assert "server_accepts_key_then_timeout" in text
    assert "publickey_offer_timeout" in text
    assert "NODE_EXPORTER=ok" in text
    assert "NODE_LOAD1_PER_CPU" in text
    assert "NODE_LOAD_CLASSIFIER" in text
    assert "DOCKER_STATS_TEXTFILE_AGE_SECONDS" in text
    assert "DOCKER_STATS_TEXTFILE_FRESHNESS" in text
    assert "SYSTEMD_UNIT unit=%s active_state=%s classifier=%s" in text
    assert "systemctl_show_timeout" in text
    assert "systemctl_timeout_budget_exhausted" in text
    assert "cat /home" not in text
    assert "cat ~/.ssh/authorized_keys" not in text
    assert "cat \"$home_dir/.ssh/authorized_keys\"" not in text
    assert "systemctl show" not in text
    assert "systemctl is-active" not in text
    assert "chmod" not in text
    assert "chown" not in text


def test_110_ssh_publickey_auth_repair_is_local_and_does_not_print_keys() -> None:
    text = SSH_AUTH_REPAIR.read_text(encoding="utf-8")

    assert "not running on 192.168.0.110" in text
    assert "--apply" in text
    assert "chmod 700" in text
    assert "chmod 600" in text
    assert "chown \"$user:$user\"" in text
    assert "sshd -t" in text
    assert "ACCOUNT_METADATA user=" in text
    assert "passwd -S" in text
    assert "account_locked=" in text
    assert "shell_executable=" in text
    assert "SSHD_EFFECTIVE_CONFIG available=true" in text
    assert "unverified_requires_root" in text
    assert "hostkeys_unavailable_or_permission" in text
    assert "sshd -T -C" in text
    assert "pubkeyauthentication=" in text
    assert "authorized_keys_file_default=" in text
    assert 'RELOAD_SSH="${RELOAD_SSH:-0}"' in text
    assert "cat \"$home_dir/.ssh/authorized_keys\"" not in text
    assert "getent shadow" not in text
    assert "echo \"$(cat" not in text
