"""Kimi CLI provider."""

from __future__ import annotations

import shutil
import subprocess
from typing import Any

from ..prompts import SYSTEM
from ..utils.logger import Logger
from .base_provider import BaseProvider


class KimiProvider(BaseProvider):
    """Provider using Kimi CLI."""

    name = "Kimi Code CLI"
    type = "cli"

    def __init__(self, model: str = "kimi-code/kimi-for-coding") -> None:
        self.model = model

    def test_connection(self) -> bool:
        """Check if kimi-cli is available."""
        try:
            kimi_path = shutil.which("kimi-cli")
            if not kimi_path:
                return False

            result = subprocess.run(
                ["kimi-cli", "--version"], capture_output=True, text=True, timeout=5
            )

            if result.returncode == 0:
                Logger.info("Kimi CLI detected", {"version": result.stdout.strip()})
                return True
            return False

        except Exception:
            return False

    def execute(self, skill_content: str, user_input: str, context: dict[str, Any]) -> str:
        """Execute task using kimi-cli."""
        system_prompt = self._build_system_prompt(skill_content, context)

        # Combine system prompt with user input (kimi-cli doesn't have --system)
        combined_prompt = f"{system_prompt}\n\nUser request: {user_input}"

        args = [
            "kimi-cli",
            "--model", self.model,
            "--prompt", combined_prompt,
            "--print",
            "--quiet",
        ]

        Logger.info("Executing with Kimi CLI", {"input": user_input[:100]})

        try:
            result = subprocess.run(
                args,
                capture_output=True,
                text=True,
                stdin=subprocess.DEVNULL,  # Avoid hanging when running in subprocess
                timeout=300,  # 5 minutes
            )

            if result.returncode == 0:
                return result.stdout.strip()
            else:
                raise RuntimeError(
                    f"Kimi CLI exited with code {result.returncode}: {result.stderr}"
                )

        except subprocess.TimeoutExpired:
            raise RuntimeError("Kimi CLI timed out after 5 minutes")
        except FileNotFoundError:
            raise RuntimeError("kimi-cli not found in PATH")

    def _build_system_prompt(self, skill_content: str, context: dict[str, Any]) -> str:
        """Build system prompt."""
        # Check if custom system prompt provided (from intent analyzer)
        custom_prompt = context.get("systemPrompt")
        if custom_prompt:
            return custom_prompt

        # Start with base system prompt
        prompt = SYSTEM

        # Add skill-specific content
        if skill_content:
            prompt += f"\n\n## Skill-Specific Instructions\n\n{skill_content}"

        skill = context.get("skill")
        if skill:
            prompt += f"\n\n## Current Task\n\nUse the {skill} skill to help the user."

        return prompt

    def get_model(self) -> str:
        """Get model name."""
        return self.model
