"""ToolDefinition — describes a registered development tool."""

from __future__ import annotations

import shutil
from dataclasses import dataclass, field
from typing import Any

from proxym.tools._enums import ToolCapability, ToolCategory
from proxym.tools._instance import ToolInstance


@dataclass
class ToolDefinition:
    """Describes a registered development tool."""
    name: str
    category: ToolCategory
    binary: str = ""                                # e.g. "aider", "claude"
    capabilities: list[ToolCapability] = field(default_factory=list)
    default_model: str = ""                         # alias like "smart" or full id
    modes: list[str] = field(default_factory=list)  # e.g. ["code", "architect", "ask"]
    config: dict[str, Any] = field(default_factory=dict)
    instances: list[ToolInstance] = field(default_factory=list)
    default_instance: str = "host"
    description: str = ""
    force_available: bool | None = None

    @property
    def is_available(self) -> bool:
        """Check tool availability.

        Uses *force_available* override first (set via PROXYM_TOOLS_AVAILABLE
        env var for containerised deployments), then falls back to binary
        detection on PATH and docker-backed instances.
        """
        if self.force_available is not None:
            return self.force_available
        if self.binary and shutil.which(self.binary) is not None:
            return True
        return any(instance.is_available for instance in self.instances)

    def summary(self) -> dict[str, Any]:
        return {
            "name": self.name,
            "category": self.category.value,
            "binary": self.binary,
            "available": self.is_available,
            "capabilities": [c.value for c in self.capabilities],
            "modes": self.modes,
            "default_model": self.default_model,
            "default_instance": self.default_instance,
            "instances": [i.summary() for i in self.instances],
            "description": self.description,
        }

    def get_instance(self, instance_name: str) -> ToolInstance | None:
        instance_name = (instance_name or "").strip()
        if not instance_name:
            return None
        for instance in self.instances:
            if instance.name == instance_name:
                return instance
        return None
