import os
import subprocess
import textwrap
from pathlib import Path


REPO_ROOT = Path(__file__).resolve().parents[4]
SELFGATE = REPO_ROOT / "recoil" / "pipeline" / "tools" / "spec_selfgate.sh"


def _write_fake_codex(path: Path, capture: Path) -> None:
    path.write_text(
        textwrap.dedent(
            f"""\
            #!/usr/bin/env python3
            import sys
            from pathlib import Path

            capture = Path({str(capture)!r})
            stdin = sys.stdin.read()
            args = sys.argv[1:]

            lines = [f"ARGV_COUNT={{len(args)}}"]
            for i, arg in enumerate(args):
                lines.append(f"ARGV[{{i}}]<<EOF")
                lines.append(arg)
                lines.append("EOF")
            lines.append("STDIN<<EOF")
            lines.append(stdin)
            lines.append("EOF")

            capture.write_text("\\n".join(lines), encoding="utf-8")
            print("MINOR: none")
            print("VERDICT: READY")
            """
        ),
        encoding="utf-8",
    )
    path.chmod(0o755)


def _valid_spec(title: str, marker: str) -> str:
    return textwrap.dedent(
        f"""\
        # BUILD_SPEC

        ## Phase 1: {title}

        {marker}

        ### Validation
        ```bash
        printf '%s\\n' ok
        ```
        """
    )


def test_review_prompt_uses_absolute_passed_spec(tmp_path: Path) -> None:
    cwd_dir = tmp_path / "cwd_dir"
    real_dir = tmp_path / "real_dir"
    bin_dir = tmp_path / "bin"
    cwd_dir.mkdir()
    real_dir.mkdir()
    bin_dir.mkdir()

    decoy_marker = "DECOY_SPEC_CONTENT_SHOULD_NOT_APPEAR"
    real_marker = "MARKER_REAL_SPEC_XYZ"
    (cwd_dir / "BUILD_SPEC.md").write_text(
        _valid_spec("Decoy", decoy_marker),
        encoding="utf-8",
    )
    real_spec = real_dir / "BUILD_SPEC.md"
    real_spec.write_text(_valid_spec("Real", real_marker), encoding="utf-8")

    capture = tmp_path / "codex-capture.txt"
    fake_codex = bin_dir / "codex"
    _write_fake_codex(fake_codex, capture)

    env = os.environ.copy()
    env["HARNESS_CODEX_BIN"] = str(fake_codex)
    result = subprocess.run(
        ["bash", str(SELFGATE), "../real_dir/BUILD_SPEC.md"],
        cwd=cwd_dir,
        env=env,
        text=True,
        capture_output=True,
        check=False,
    )

    assert result.returncode == 0, result.stderr + result.stdout
    captured = capture.read_text(encoding="utf-8")
    assert str(real_spec) in captured
    assert "Do NOT read BUILD_SPEC.md from the current working directory" in captured
    assert decoy_marker not in captured


def test_precheck_fail_exits_nonzero(tmp_path: Path) -> None:
    malformed = tmp_path / "BUILD_SPEC.md"
    malformed.write_text(
        textwrap.dedent(
            """\
            # BUILD_SPEC

            This spec has no harness-dispatchable phase headings.

            ### Validation
            ```bash
            true
            ```
            """
        ),
        encoding="utf-8",
    )

    capture = tmp_path / "codex-capture.txt"
    fake_codex = tmp_path / "codex"
    _write_fake_codex(fake_codex, capture)

    env = os.environ.copy()
    env["HARNESS_CODEX_BIN"] = str(fake_codex)
    result = subprocess.run(
        ["bash", str(SELFGATE), str(malformed)],
        cwd=tmp_path,
        env=env,
        text=True,
        capture_output=True,
        check=False,
    )

    combined = result.stdout + result.stderr
    assert result.returncode != 0
    assert "PRECHECK" in combined or "not dispatchable" in combined
    assert not capture.exists()
