import os
import subprocess
from pathlib import Path
from .base import BaseAgentRunner, AgentResult


class CopilotRunner(BaseAgentRunner):
    def __init__(self, token: str = ""):
        self.token = token

    def run_task(self, repo_path: Path, prompt: str) -> AgentResult:
        cmd = [
            "copilot",
            "--autopilot",
            "--yolo",
            "-p",
            prompt,
        ]

        env = self.get_sanitized_env()
        # Copilot CLI podporuje COPILOT_GITHUB_TOKEN, GH_TOKEN a GITHUB_TOKEN
        token = os.environ.get("COPILOT_GITHUB_TOKEN") or self.token or os.environ.get("GH_TOKEN")
        if token:
            env["COPILOT_GITHUB_TOKEN"] = token
            env["GH_TOKEN"] = token
            env["GITHUB_TOKEN"] = token

        try:
            proc = subprocess.run(
                cmd,
                cwd=str(repo_path),
                env=env,
                capture_output=True,
                text=True,
                timeout=900,
            )
            output = (proc.stdout + "\n" + proc.stderr).strip()
            return AgentResult(success=(proc.returncode == 0), output=output or "Úkol dokončen.")
        except Exception as e:
            return AgentResult(success=False, output=f"Chyba při běhu GitHub Copilot: {e}")
