#!/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-110-controlled-cd-lane-drain.sh"


def _make_lane(tmp_path: Path) -> dict[str, str]:
    lane_dir = tmp_path / "awoooi-cd-lane-drain"
    workdir = lane_dir / "data"
    workdir.mkdir(parents=True)
    binary = lane_dir / "awoooi_cd_lane_controlled"
    binary.write_text("#!/usr/bin/env bash\nexit 99\n", encoding="utf-8")
    binary.chmod(0o755)
    config = lane_dir / "config.yaml"
    config.write_text(
        "\n".join(
            [
                "runner:",
                "  capacity: 1",
                "  labels:",
                '    - "awoooi-host:host"',
                '    - "awoooi-ubuntu:docker://192.168.0.110:5000/awoooi/ci-runner:act-22.04"',
                "",
            ]
        ),
        encoding="utf-8",
    )
    return {
        "RUNNER_DIR": str(lane_dir),
        "RUNNER_WORKDIR": str(workdir),
        "RUNNER_BINARY": str(binary),
        "RUNNER_CONFIG": str(config),
        "RUNNER_REGISTRATION": str(workdir / ".runner"),
        "READINESS_VERIFIER": str(tmp_path / "missing-verifier"),
    }


def test_110_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 "Do not pipe the script over stdin" in text
    assert "REQUIRE_ACTIVE_SERVICE=0" in text


def test_110_register_helper_rejects_runner_token_env(tmp_path: Path) -> None:
    env = {**os.environ, **_make_lane(tmp_path), "RUNNER_TOKEN": "fake-token-must-not-leak"}

    result = subprocess.run(
        ["bash", str(REGISTER), "--check"],
        check=False,
        env=env,
        text=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
    )

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


def test_110_register_helper_dry_run_requires_no_token(tmp_path: Path) -> None:
    result = subprocess.run(
        ["bash", str(REGISTER), "--check"],
        check=False,
        env={**os.environ, **_make_lane(tmp_path)},
        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


def test_110_register_helper_existing_registration_does_not_read_content(tmp_path: Path) -> None:
    env = {**os.environ, **_make_lane(tmp_path)}
    Path(env["RUNNER_REGISTRATION"]).write_text("secret-like-registration-content\n", encoding="utf-8")

    result = subprocess.run(
        ["bash", str(REGISTER), "--check"],
        check=False,
        env=env,
        text=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
    )

    assert result.returncode == 0
    assert "runner_registration_present=1" in result.stdout
    assert "runner_registration_content_read=false" in result.stdout
    assert "secret-like-registration-content" not in result.stdout
    assert "secret-like-registration-content" not in result.stderr
    assert "safe_next_step=enable_awoooi_cd_lane_drain_service_and_rerun_110_readiness_verifier" in result.stdout


def test_110_register_helper_enable_service_dry_run_does_not_call_systemctl(tmp_path: Path) -> None:
    fake_bin = tmp_path / "bin"
    fake_bin.mkdir()
    systemctl = fake_bin / "systemctl"
    systemctl.write_text(
        "#!/usr/bin/env bash\nprintf 'systemctl_must_not_run\\n' >&2\nexit 44\n",
        encoding="utf-8",
    )
    systemctl.chmod(0o755)
    env = {
        **os.environ,
        **_make_lane(tmp_path),
        "PATH": f"{fake_bin}:{os.environ['PATH']}",
    }
    Path(env["RUNNER_REGISTRATION"]).write_text("secret-like-registration-content\n", encoding="utf-8")

    result = subprocess.run(
        ["bash", str(REGISTER), "--check", "--enable-service"],
        check=False,
        env=env,
        text=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
    )

    assert result.returncode == 0
    assert "dry_run=true" in result.stdout
    assert "safe_next_step=enable_service_after_registration_with_verifier" in result.stdout
    assert "systemctl_must_not_run" not in result.stderr
