from pathlib import Path

from pydantic import ValidationError

from dual_agent.infra.process import ProcessRunner, collect_secrets, run_with_secrets

from .base import AgentRequest, AgentResult
from .fake import SCHEMAS


class CommandAgentAdapter:
    def __init__(self, argv: list[str], log_root: str | Path, timeout_s: float = 900) -> None:
        self.argv = argv
        self.runner = ProcessRunner(log_root)
        self.timeout_s = timeout_s

    def command(self, request: AgentRequest) -> list[str]:
        return [*self.argv, request.goal]

    def run(self, request: AgentRequest, on_start=None) -> AgentResult:
        result = run_with_secrets(self.runner,
            self.command(request), request.worktree_path, self.timeout_s,
            on_start=on_start, secrets=collect_secrets(),
        )
        if result.status == "TIMEOUT":
            return AgentResult("TIMEOUT", error="agent process timed out")
        if result.status != "SUCCESS":
            return AgentResult("AGENT_FAILURE", error=f"agent exited with {result.exit_code}")
        try:
            artifact = SCHEMAS[request.stage].model_validate_json(result.stdout_path.read_text(encoding="utf-8").strip())
            return AgentResult("SUCCESS", artifact=artifact)
        except (KeyError, ValidationError, ValueError) as error:
            return AgentResult("PROTOCOL", error=str(error))
