"""ToolInstance — concrete runtime instance for a registered tool."""

from __future__ import annotations

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


@dataclass
class ToolInstance:
    """Concrete runtime instance for a registered tool."""
    name: str
    kind: str  # "host", "docker", "kvm", "vm"
    command: list[str] = field(default_factory=list)
    service: str = ""
    profile: str = ""
    container_name: str = ""
    vm_name: str = ""           # KVM/QEMU VM name
    vm_host: str = ""           # VM host/IP for SSH
    vm_user: str = ""           # SSH user for VM
    vm_ssh_port: int = 22       # SSH port for VM
    description: str = ""
    notes: str = ""
    force_available: bool | None = None

    @property
    def is_available(self) -> bool:
        if self.force_available is not None:
            return self.force_available
        if self.kind == "docker":
            return shutil.which("docker") is not None
        if self.kind in ("kvm", "vm"):
            return self._check_vm_available()
        if self.command:
            return shutil.which(self.command[0]) is not None
        return False

    def _check_vm_available(self) -> bool:
        """Check if KVM/VM instance is available via SSH or virsh."""
        # Check if we can connect via SSH to the VM
        if self.vm_host and self.vm_user:
            try:
                result = subprocess.run(
                    ["ssh", "-o", "ConnectTimeout=2", "-o", "BatchMode=yes",
                     f"{self.vm_user}@{self.vm_host}", "echo", "available"],
                    capture_output=True,
                    timeout=5,
                )
                return result.returncode == 0 and b"available" in result.stdout
            except (subprocess.TimeoutExpired, FileNotFoundError):
                pass
        # Check via virsh if VM name is provided and host has libvirt
        if self.vm_name and shutil.which("virsh"):
            try:
                result = subprocess.run(
                    ["virsh", "domstate", self.vm_name],
                    capture_output=True,
                    timeout=3,
                )
                return result.returncode == 0 and b"running" in result.stdout.lower()
            except (subprocess.TimeoutExpired, FileNotFoundError):
                pass
        return False

    def summary(self) -> dict[str, Any]:
        return {
            "name": self.name,
            "kind": self.kind,
            "command": self.command,
            "service": self.service,
            "profile": self.profile,
            "container_name": self.container_name,
            "vm_name": self.vm_name,
            "vm_host": self.vm_host,
            "vm_user": self.vm_user,
            "vm_ssh_port": self.vm_ssh_port,
            "description": self.description,
            "notes": self.notes,
            "available": self.is_available,
        }
