"""Tests for harness/agent_adapter.py command construction."""

from __future__ import annotations

import shutil
import subprocess
import uuid
from contextlib import contextmanager
from pathlib import Path

from harness import agent_adapter


@contextmanager
def _tmp_workspace():
    base_root = Path(__file__).resolve().parents[1] / ".test-artifacts"
    base_root.mkdir(exist_ok=True)
    workspace = base_root / f"agent-adapter-{uuid.uuid4().hex}"
    workspace.mkdir()
    try:
        yield workspace
    finally:
        shutil.rmtree(workspace, ignore_errors=True)


def test_no_dollar_cat_in_presets():
    for preset in agent_adapter.AGENT_PRESETS.values():
        assert "$(cat " not in preset.command_template


def test_prompt_content_placeholder():
    for preset_name in ("gemini", "copilot", "claude"):
        assert "{prompt_content}" in agent_adapter.AGENT_PRESETS[preset_name].command_template


def test_codex_uses_stdin_placeholder():
    assert "{stdin}" in agent_adapter.AGENT_PRESETS["codex"].command_template


def test_command_build_substitutes_content(monkeypatch):
    prompt = 'line one with "quotes"\nline two with $PATH'
    captured = {}

    def fake_run(cmd, **kwargs):
        captured["cmd"] = cmd
        captured["kwargs"] = kwargs
        return subprocess.CompletedProcess(cmd, 0, stdout="ok", stderr="")

    monkeypatch.setattr(agent_adapter.subprocess, "run", fake_run)
    monkeypatch.setattr(agent_adapter, "_auto_commit_if_needed", lambda workspace_dir: False)

    with _tmp_workspace() as workspace_dir:
        result = agent_adapter.run_agent_on_workspace(
            adapter=agent_adapter.AGENT_PRESETS["gemini"],
            workspace_dir=workspace_dir,
            prompt=prompt,
            behavior_id="BHV-001",
        )

    assert result.success is True
    assert captured["kwargs"]["shell"] is False
    assert isinstance(captured["cmd"], list)
    assert prompt in captured["cmd"]
    assert not any("$(cat " in part for part in captured["cmd"])


def test_command_build_codex_uses_stdin(monkeypatch):
    """Codex adapter pipes prompt via stdin (shell=True, input=prompt)."""
    captured = {}

    def fake_run(cmd, **kwargs):
        captured["cmd"] = cmd
        captured["kwargs"] = kwargs
        return subprocess.CompletedProcess(cmd, 0, stdout="ok", stderr="")

    monkeypatch.setattr(agent_adapter.subprocess, "run", fake_run)
    monkeypatch.setattr(agent_adapter, "_auto_commit_if_needed", lambda workspace_dir: False)

    with _tmp_workspace() as workspace_dir:
        agent_adapter.run_agent_on_workspace(
            adapter=agent_adapter.AGENT_PRESETS["codex"],
            workspace_dir=workspace_dir,
            prompt="fix the bug",
            behavior_id="BHV-002",
        )

        assert captured["kwargs"]["shell"] is True
        assert isinstance(captured["cmd"], str)
        # Prompt piped via stdin, "-" tells codex to read from stdin
        assert captured["kwargs"]["input"] == "fix the bug"
        assert " - " in captured["cmd"] or captured["cmd"].endswith(" -")
        assert "{stdin}" not in captured["cmd"]
