from __future__ import annotations

import os
import subprocess
from dataclasses import dataclass
from pathlib import Path

from .base import Patcher, PatchResult


@dataclass(frozen=True)
class CommandPatcher(Patcher):
    """Run a local command that prints a unified diff to stdout."""

    cmd: str
    name: str = "command"

    def propose_patch(self, *, prompt: str, context_dir: Path, cwd: Path) -> PatchResult:
        env = os.environ.copy()
        env["LLMDEBUG_EVAL_CONTEXT_DIR"] = str(context_dir)
        env.setdefault("LLMDEBUG_EVAL_PROMPT_FILE", str(context_dir / "prompt.txt"))
        proc = subprocess.run(
            self.cmd,
            input=prompt,
            text=True,
            shell=True,
            cwd=cwd,
            env=env,
            capture_output=True,
        )
        diff = proc.stdout.strip() or None
        meta = {
            "returncode": proc.returncode,
            "stderr": proc.stderr.strip(),
        }
        return PatchResult(diff=diff, meta=meta)


def patcher_from_env() -> CommandPatcher | None:
    cmd = os.getenv("LLMDEBUG_EVAL_PATCH_CMD", "").strip()
    return CommandPatcher(cmd=cmd) if cmd else None
