"""VM configuration dataclasses."""

from __future__ import annotations

import fnmatch
import time
from dataclasses import dataclass, field

from proxym.virt._enums import VMState


@dataclass
class ProjectsConfig:
    """Configuration for shared project mounts from the host."""
    root: str = "~/github"                     # projects_root on host
    guest_mount: str = "/home/dev/github"      # mount point inside VM
    include: list[str] = field(default_factory=list)  # glob patterns to include
    exclude: list[str] = field(default_factory=list)  # glob patterns to exclude

    def filter_projects(self, projects: list[str]) -> list[str]:
        """Filter project names by include/exclude patterns."""
        result = projects
        if self.include:
            result = [p for p in result
                      if any(fnmatch.fnmatch(p, pat) for pat in self.include)]
        if self.exclude:
            result = [p for p in result
                      if not any(fnmatch.fnmatch(p, pat) for pat in self.exclude)]
        return result


@dataclass
class VMConfig:
    """Configuration for a development VM."""
    id: str = ""
    name: str = ""                       # e.g., "windsurf-work"
    account_id: str = ""                 # linked account
    tool: str = ""                       # tool type
    backend: str = "auto"                # "clonebox" | "virsh" | "auto"

    # Resources
    vcpus: int = 4
    memory_mb: int = 6144
    disk_gb: int = 20

    # Base image
    base_image: str = "ubuntu-24.04"     # qcow2 base or clonebox image
    overlay_path: str = ""               # cow overlay per VM

    # Mounts: host → VM
    code_mount_host: str = ""            # e.g., /home/user/github
    code_mount_guest: str = "/home/dev/github"  # mount point in VM

    # Projects filtering
    projects_include: list[str] = field(default_factory=list)
    projects_exclude: list[str] = field(default_factory=list)

    # Networking
    proxy_address: str = "10.0.0.1:4000"  # AI proxy on host
    forward_ports: list[int] = field(default_factory=lambda: [3000, 8080])

    # Browser profile
    browser_profile_id: str = ""          # maps to account's browser profile
    browser_profile_path: str = ""        # inside VM, persisted as overlay
    preserve_browser_cache: bool = True

    # State
    state: VMState = VMState.STOPPED
    created_at: float = field(default_factory=time.time)
    last_started_at: float = 0.0
    snapshot_name: str = ""


@dataclass
class VMStatus:
    """Runtime status of a VM."""
    id: str
    name: str
    state: VMState
    account_id: str
    tool: str
    backend: str = "virsh"
    uptime_seconds: float = 0
    cpu_usage_pct: float = 0
    memory_used_mb: int = 0
    code_mount: str = ""
    ip_address: str = ""
