import os
import shlex
from pathlib import Path

from harbor.agents.installed.base import BaseInstalledAgent, ExecInput
from harbor.models.agent.context import AgentContext
from harbor.models.agent.name import AgentName


class OpenCode(BaseInstalledAgent):
    """
    The OpenCode agent uses the opencode-ai tool to solve tasks.
    """

    @staticmethod
    def name() -> str:
        return AgentName.OPENCODE.value

    @property
    def _install_agent_template_path(self) -> Path:
        return Path(__file__).parent / "install-opencode.sh.j2"

    def populate_context_post_run(self, context: AgentContext) -> None:
        pass

    def create_run_agent_commands(self, instruction: str) -> list[ExecInput]:
        escaped_instruction = shlex.quote(instruction)

        if not self.model_name or "/" not in self.model_name:
            raise ValueError("Model name must be in the format provider/model_name")

        provider, _ = self.model_name.split("/", 1)

        env = {}
        keys = []

        # Get provider environment variables
        if provider == "amazon-bedrock":
            keys.extend(["AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_REGION"])
        elif provider == "anthropic":
            keys.append("ANTHROPIC_API_KEY")
        elif provider == "azure":
            keys.extend(["AZURE_RESOURCE_NAME", "AZURE_API_KEY"])
        elif provider == "deepseek":
            keys.append("DEEPSEEK_API_KEY")
        elif provider == "github-copilot":
            keys.append("GITHUB_TOKEN")
        elif provider == "google":
            keys.extend(
                [
                    "GEMINI_API_KEY",
                    "GOOGLE_GENERATIVE_AI_API_KEY",
                    "GOOGLE_APPLICATION_CREDENTIALS",
                    "GOOGLE_CLOUD_PROJECT",
                    "GOOGLE_CLOUD_LOCATION",
                    "GOOGLE_GENAI_USE_VERTEXAI",
                    "GOOGLE_API_KEY",
                ]
            )
        elif provider == "groq":
            keys.append("GROQ_API_KEY")
        elif provider == "huggingface":
            keys.append("HF_TOKEN")
        elif provider == "llama":
            keys.append("LLAMA_API_KEY")
        elif provider == "mistral":
            keys.append("MISTRAL_API_KEY")
        elif provider == "openai":
            keys.append("OPENAI_API_KEY")
        elif provider == "xai":
            keys.append("XAI_API_KEY")
        else:
            raise ValueError(
                f"Unknown provider {provider}. If you believe this provider "
                "should be supported, please contact the maintainers."
            )

        for key in keys:
            if key in os.environ:
                env[key] = os.environ[key]

        # Enable fake VCS for OpenCode
        env["OPENCODE_FAKE_VCS"] = "git"

        return [
            ExecInput(
                command=(
                    f"opencode --model {self.model_name} run {escaped_instruction} "
                    f"2>&1 | tee /logs/agent/opencode.txt"
                ),
                env=env,
            )
        ]
