#!/usr/bin/env python3
from __future__ import annotations

import os
import subprocess
from pathlib import Path


ROOT = Path(__file__).resolve().parents[2]
REGISTER = ROOT / "ops/runner/register-awoooi-non110-runner.sh"
COMPAT_WRAPPER = ROOT / "ops/runner/install-awoooi-non110-user-runner.sh"
USER_SERVICE_INSTALLER = ROOT / "ops/runner/install-awoooi-non110-runner-user-service.sh"


def test_register_helper_has_no_token_argv_path() -> None:
    text = REGISTER.read_text(encoding="utf-8")
    assert "--token" not in text
    assert "runner_token_env_not_allowed" in text
    assert "runner_token_in_argv=false" in text
    assert "runner_token_echoed=false" in text
    assert "raw_runner_registration_read=false" in text
    assert "Copy this script to the target host first" in text
    assert "Do not pipe the script over stdin" in text


def test_register_helper_rejects_runner_token_env(tmp_path: Path) -> None:
    runner_dir = tmp_path / "runner"
    runner_dir.mkdir(parents=True)
    binary = runner_dir / "act_runner"
    binary.write_text("#!/usr/bin/env bash\nexit 99\n", encoding="utf-8")
    binary.chmod(0o755)
    config = runner_dir / "config.yaml"
    config.write_text("runner:\n  capacity: 1\n", encoding="utf-8")

    result = subprocess.run(
        ["bash", str(REGISTER), "--check"],
        check=False,
        env={
            **os.environ,
            "RUNNER_TOKEN": "fake-token-that-must-not-be-accepted",
            "RUNNER_DIR": str(runner_dir),
            "RUNNER_BINARY": str(binary),
            "RUNNER_CONFIG": str(config),
            "RUNNER_REGISTRATION": str(runner_dir / ".runner"),
        },
        text=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
    )

    assert result.returncode != 0
    assert "runner_token_env_not_allowed" in result.stderr
    assert "fake-token-that-must-not-be-accepted" not in result.stdout
    assert "fake-token-that-must-not-be-accepted" not in result.stderr


def test_user_installer_has_no_token_argv_path() -> None:
    wrapper = COMPAT_WRAPPER.read_text(encoding="utf-8")
    installer = USER_SERVICE_INSTALLER.read_text(encoding="utf-8")
    assert "--token" not in wrapper
    assert "--token" not in installer
    assert "retired_wrapper_does_not_register_or_start_runner" in wrapper
    assert "never\n# registers a runner" in installer


def test_runner_readme_keeps_token_out_of_chat() -> None:
    readme = (ROOT / "ops/runner/README.md").read_text(encoding="utf-8")
    assert "不要使用 Personal Access Token 或 API token" in readme
    assert "不要把 token" in readme
    assert "hidden TTY prompt" in readme


def test_user_installer_autostarts_only_after_registration_metadata() -> None:
    installer = USER_SERVICE_INSTALLER.read_text(encoding="utf-8")
    assert "AUTOSTART_PATH_NAME" in installer
    assert "PathExists=${RUNNER_REGISTRATION}" in installer
    assert "Unit=${AUTOSTART_SERVICE_NAME}" in installer
    assert "ExecStart=/usr/bin/test -s ${RUNNER_REGISTRATION}" in installer
    assert "ExecStart=/usr/bin/touch ${ENABLE_SENTINEL}" in installer
    assert "systemctl --user enable --now ${SERVICE_NAME}" in installer
    assert 'systemctl --user enable --now "$AUTOSTART_PATH_NAME"' in installer
    assert 'systemctl --user disable "$AUTOSTART_PATH_NAME"' in installer


def test_register_helper_dry_run_requires_no_token(tmp_path: Path) -> None:
    runner_dir = tmp_path / "runner"
    runner_dir.mkdir(parents=True)
    binary = runner_dir / "act_runner"
    binary.write_text("#!/usr/bin/env bash\nexit 99\n", encoding="utf-8")
    binary.chmod(0o755)
    config = runner_dir / "config.yaml"
    config.write_text("runner:\n  capacity: 1\n", encoding="utf-8")

    result = subprocess.run(
        ["bash", str(REGISTER), "--check"],
        check=False,
        env={
            **os.environ,
            "RUNNER_DIR": str(runner_dir),
            "RUNNER_BINARY": str(binary),
            "RUNNER_CONFIG": str(config),
            "RUNNER_REGISTRATION": str(runner_dir / ".runner"),
        },
        text=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
    )

    assert result.returncode == 0
    assert "dry_run=true" in result.stdout
    assert "safe_next_step=run_this_script_from_interactive_tty_without_capturing_token" in result.stdout
    assert "runner_token_in_argv=false" in result.stdout
    assert "--token" not in result.stdout
    assert "fake-token" not in result.stdout
