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

import os
import subprocess
from pathlib import Path


ROOT = Path(__file__).resolve().parents[2]
VERIFIER = ROOT / "ops/runner/check-awoooi-110-controlled-cd-lane-readiness.sh"


def _write_fake_bin(path: Path, name: str, body: str) -> None:
    target = path / name
    target.write_text(body, encoding="utf-8")
    target.chmod(0o755)


def _write_config(path: Path, *, forbidden_label: bool = False) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    labels = [
        '    - "awoooi-host:host"',
        '    - "awoooi-ubuntu:docker://192.168.0.110:5000/awoooi/ci-runner:act-22.04"',
    ]
    if forbidden_label:
        labels.append('    - "ubuntu-latest:docker://node:22"')
    path.write_text(
        "\n".join(
            [
                "runner:",
                "  capacity: 1",
                "  labels:",
                *labels,
                "",
            ]
        ),
        encoding="utf-8",
    )


def _write_unit(
    path: Path,
    *,
    binary: Path,
    config: Path,
    registration: Path,
    include_registration_condition: bool = True,
) -> None:
    condition = f"ConditionPathExists={registration}\n" if include_registration_condition else ""
    path.write_text(
        f"""
[Unit]
Description=AWOOOI controlled CD lane drain
After=network-online.target docker.service
Wants=network-online.target
Requires=docker.service
{condition}
[Service]
Type=simple
User=wooo
WorkingDirectory={binary.parent}/data
Environment=HOME=/home/wooo
Environment=AWOOOI_CONTROLLED_RUNNER_OPEN=1
ExecStart={binary} daemon --config {config}
Restart=always
RestartSec=10
KillSignal=SIGINT
TimeoutStopSec=3700
SuccessExitStatus=0 130 143
CPUAccounting=true
CPUQuota=250%
MemoryAccounting=true
MemoryHigh=8G
MemoryMax=12G
TasksAccounting=true
TasksMax=512
NoNewPrivileges=true
""".strip()
        + "\n",
        encoding="utf-8",
    )


def _run_verifier(
    tmp_path: Path,
    *,
    registration_present: bool = True,
    forbidden_label: bool = False,
    active_service: bool = True,
    include_registration_condition: bool = True,
    legacy_active: bool = False,
) -> subprocess.CompletedProcess[str]:
    fake_bin = tmp_path / "bin"
    unit_dir = tmp_path / "units"
    root_restore = tmp_path / "root"
    lane_dir = tmp_path / "awoooi-cd-lane-drain"
    data_dir = lane_dir / "data"
    fake_bin.mkdir()
    unit_dir.mkdir()
    root_restore.mkdir()
    data_dir.mkdir(parents=True)

    binary = lane_dir / "awoooi_cd_lane_controlled"
    config = lane_dir / "config.yaml"
    registration = data_dir / ".runner"
    binary.write_bytes(b"\x7fELF controlled test binary\n")
    binary.chmod(0o755)
    _write_config(config, forbidden_label=forbidden_label)
    if registration_present:
        registration.write_text("secret-token-like-content-not-printed\n", encoding="utf-8")
    _write_unit(
        unit_dir / "awoooi-cd-lane-drain.service",
        binary=binary,
        config=config,
        registration=registration,
        include_registration_condition=include_registration_condition,
    )

    legacy_state = "active" if legacy_active else "inactive"
    legacy_pid = "4321" if legacy_active else "0"
    _write_fake_bin(
        fake_bin,
        "systemctl",
        f"""#!/usr/bin/env bash
set -euo pipefail
cmd="${{1:-}}"; unit="${{2:-}}"
case "$cmd" in
  show)
    unit="${{2:-}}"
    if [ -f "{unit_dir}/$unit" ]; then
      printf 'LoadState=loaded\\nActiveState={"active" if active_service else "inactive"}\\nUnitFileState=enabled\\nMainPID={"1234" if active_service else "0"}\\n'
      exit 0
    fi
    case "$unit" in
      awoooi-cd-lane.service)
        printf 'LoadState=masked\\nActiveState=inactive\\nUnitFileState=masked\\nMainPID=0\\n'
        exit 0
        ;;
      awoooi-direct-runner-open.service|awoooi-direct-runner.service|gitea-act-runner-host.service|gitea-act-runner-awoooi-controlled.service|gitea-awoooi-controlled-runner.service|gitea-act-runner-awoooi-open.service)
        printf 'LoadState=%s\\nActiveState=%s\\nUnitFileState=%s\\nMainPID=%s\\n' '{"loaded" if legacy_active else "masked"}' "{legacy_state}" '{"enabled" if legacy_active else "masked"}' "{legacy_pid}"
        exit 0
        ;;
    esac
    printf 'LoadState=not-found\\nActiveState=inactive\\nUnitFileState=\\nMainPID=0\\n'
    exit 0
    ;;
  cat)
    if [ -f "{unit_dir}/$unit" ]; then cat "{unit_dir}/$unit"; exit 0; fi
    exit 1
    ;;
esac
exit 1
""",
    )
    _write_fake_bin(
        fake_bin,
        "sudo",
        """#!/usr/bin/env bash
set -euo pipefail
if [ "${1:-}" = "-n" ] && [ "${2:-}" = "-u" ]; then
  shift 3
fi
exec "$@"
""",
    )
    _write_fake_bin(
        fake_bin,
        "runuser",
        """#!/usr/bin/env bash
set -euo pipefail
if [ "${1:-}" = "-u" ]; then
  shift 2
fi
if [ "${1:-}" = "--" ]; then
  shift
fi
exec "$@"
""",
    )
    _write_fake_bin(
        fake_bin,
        "ip",
        """#!/usr/bin/env bash
if [ "${1:-}" = "-o" ] && [ "${2:-}" = "-4" ] && [ "${3:-}" = "addr" ]; then
  printf '2: eth0  inet 192.168.0.110/24 brd 192.168.0.255 scope global eth0\\n'
  exit 0
fi
exit 1
""",
    )
    _write_fake_bin(
        fake_bin,
        "docker",
        """#!/usr/bin/env bash
if [ "${1:-}" = "ps" ]; then exit 0; fi
exit 0
""",
    )
    _write_fake_bin(
        fake_bin,
        "pgrep",
        """#!/usr/bin/env bash
exit 1
""",
    )
    _write_fake_bin(
        fake_bin,
        "file",
        f"""#!/usr/bin/env bash
case "${{*:-}}" in
  *"{binary}") printf 'ELF 64-bit LSB executable\\n'; exit 0 ;;
esac
printf 'POSIX shell script\\n'
""",
    )

    env = {
        **os.environ,
        "PATH": f"{fake_bin}:{os.environ['PATH']}",
        "CD_LANE_DRAIN_DIR": str(lane_dir),
        "CD_LANE_DRAIN_BINARY": str(binary),
        "CD_LANE_DRAIN_CONFIG": str(config),
        "CD_LANE_DRAIN_REGISTRATION_PATHS": str(registration),
        "ROOT_RESTORE_PARENT": str(root_restore),
        "LEGACY_RUNNER_BINARY_PATHS": str(tmp_path / "legacy_act_runner"),
        "MAX_HEAVY_PROCESS_COUNT": "0",
        "MAX_ACTIVE_ACTION_CONTAINERS": "0",
    }
    return subprocess.run(
        ["bash", str(VERIFIER)],
        check=False,
        env=env,
        text=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
    )


def test_110_controlled_cd_lane_ready_without_printing_registration_content(
    tmp_path: Path,
) -> None:
    result = _run_verifier(tmp_path)

    assert result.returncode == 0, result.stdout + result.stderr
    assert "AWOOOI_110_CONTROLLED_CD_LANE_READY=1" in result.stdout
    assert "SERVICE_GUARDRAILS_READY=1" in result.stdout
    assert "runner_token_read=false" in result.stdout
    assert "raw_runner_registration_read=false" in result.stdout
    assert "content_read=false" in result.stdout
    assert "service_user=wooo" in result.stdout
    assert "service_user_readable=1" in result.stdout
    assert "service_user_executable=1" in result.stdout
    assert "secret-token-like-content" not in result.stdout
    assert "CD_LANE_SERVICE_GUARDRAILS" in result.stdout
    assert "registration_condition=1" in result.stdout
    assert (
        "safe_next_step=rerun_harbor_110_local_repair_queue_readback_and_non110_cd_closure_verifier"
        in result.stdout
    )


def test_110_controlled_cd_lane_blocks_missing_registration(tmp_path: Path) -> None:
    result = _run_verifier(tmp_path, registration_present=False)

    assert result.returncode == 1
    assert "BLOCKER controlled_cd_lane_registration_missing" in result.stdout
    assert "AWOOOI_110_CONTROLLED_CD_LANE_READY=0" in result.stdout
    assert (
        "safe_next_step=restore_or_register_awoooi_cd_lane_drain_registration_without_printing_token_then_rerun_this_verifier"
        in result.stdout
    )


def test_110_controlled_cd_lane_blocks_forbidden_generic_label(tmp_path: Path) -> None:
    result = _run_verifier(tmp_path, forbidden_label=True)

    assert result.returncode == 1
    assert "BLOCKER controlled_cd_lane_forbidden_label:ubuntu-latest" in result.stdout
    assert "BLOCKER controlled_cd_lane_unexpected_label:ubuntu-latest" in result.stdout
    assert "AWOOOI_110_CONTROLLED_CD_LANE_READY=0" in result.stdout


def test_110_controlled_cd_lane_requires_registration_condition(tmp_path: Path) -> None:
    result = _run_verifier(tmp_path, include_registration_condition=False)

    assert result.returncode == 1
    assert "BLOCKER controlled_cd_lane_service_registration_condition_missing" in result.stdout
    assert "SERVICE_GUARDRAILS_READY=0" in result.stdout
    assert "AWOOOI_110_CONTROLLED_CD_LANE_READY=0" in result.stdout


def test_110_controlled_cd_lane_prioritizes_staging_before_registration(
    tmp_path: Path,
) -> None:
    result = _run_verifier(
        tmp_path,
        registration_present=False,
        include_registration_condition=False,
    )

    assert result.returncode == 1
    assert "BLOCKER controlled_cd_lane_registration_missing" in result.stdout
    assert "BLOCKER controlled_cd_lane_service_registration_condition_missing" in result.stdout
    assert "SERVICE_GUARDRAILS_READY=0" in result.stdout
    assert (
        "safe_next_step=restore_awoooi_cd_lane_drain_staging_artifacts_then_rerun_this_verifier"
        in result.stdout
    )


def test_110_controlled_cd_lane_blocks_active_legacy_runner(tmp_path: Path) -> None:
    result = _run_verifier(tmp_path, legacy_active=True)

    assert result.returncode == 1
    assert "BLOCKER legacy_runner_unit_not_failclosed:gitea-act-runner-host.service" in result.stdout
    assert "AWOOOI_110_CONTROLLED_CD_LANE_READY=0" in result.stdout


def test_110_controlled_cd_lane_verifier_checks_service_user_access() -> None:
    text = VERIFIER.read_text(encoding="utf-8")

    assert "CD_LANE_DRAIN_USER" in text
    assert "service_user_test -r \"$CD_LANE_DRAIN_CONFIG\"" in text
    assert "service_user_test -x \"$CD_LANE_DRAIN_BINARY\"" in text
    assert "service_user_test -r \"$registration\"" in text
    assert "SERVICE_GUARDRAILS_READY" in text
    assert "restore_awoooi_cd_lane_drain_staging_artifacts_then_rerun_this_verifier" in text
    assert "controlled_cd_lane_config_not_readable_by_service_user" in text
    assert "controlled_cd_lane_binary_not_executable_by_service_user" in text
    assert "controlled_cd_lane_registration_not_readable_by_service_user" in text
