from __future__ import annotations

import subprocess
import sys
from pathlib import Path


REPO_ROOT = Path(__file__).resolve().parents[1]
HOOK = REPO_ROOT / "hooks" / "codex" / "portable-paths-scan.py"


def _run(args: list[str], cwd: Path | None = None) -> subprocess.CompletedProcess[str]:
    return subprocess.run(
        [sys.executable, str(HOOK), *args],
        cwd=cwd or REPO_ROOT,
        text=True,
        capture_output=True,
        check=False,
    )


def _write(path: Path, text: str) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(text, "utf-8")


def test_portable_paths_audit_blocks_user_home_path(tmp_path: Path) -> None:
    doc = tmp_path / "README.md"
    _write(doc, "Run `tool --repo /Users/terry/Project/demo`.\n")

    proc = _run(["--paths", str(doc)])
    output = f"{proc.stdout}\n{proc.stderr}"

    assert proc.returncode == 1, output
    assert "portable-paths: machine-local home paths found" in output
    assert "$HOME/Project/demo" in output
    assert "fix:" in output


def test_portable_paths_audit_allows_container_home_paths(tmp_path: Path) -> None:
    doc = tmp_path / "docker" / "agent-env" / "README.md"
    _write(doc, "Mount secrets at `/home/agent/codex_secrets`.\n")

    proc = _run(["--paths", str(doc)])
    output = f"{proc.stdout}\n{proc.stderr}"

    assert proc.returncode == 0, output
    assert "clean" in output


def test_portable_paths_audit_tracked_mode_skips_archived_plans(
    tmp_path: Path,
) -> None:
    _write(
        tmp_path / "docs" / "plans" / "old" / "old-plan.md",
        "Historical evidence: `/Users/terry/out/log.txt`.\n",
    )
    _write(tmp_path / "skills" / "demo" / "SKILL.md", "# Demo\n\nUse `$HOME/bin`.\n")
    subprocess.run(["git", "init"], cwd=tmp_path, check=True, capture_output=True)
    subprocess.run(["git", "add", "-A"], cwd=tmp_path, check=True, capture_output=True)

    proc = _run(["--tracked"], cwd=tmp_path)
    output = f"{proc.stdout}\n{proc.stderr}"

    assert proc.returncode == 0, output
    assert "clean" in output


def test_check_sh_portable_paths_mode_runs() -> None:
    proc = subprocess.run(
        ["bash", "scripts/check.sh", "--portable-paths"],
        cwd=REPO_ROOT,
        text=True,
        capture_output=True,
        check=False,
    )
    output = f"{proc.stdout}\n{proc.stderr}"

    assert proc.returncode == 0, output
    assert "lint: portable path audit" in output
    assert "portable-paths: scanned" in output
