"""MCP tools — VM management."""
from __future__ import annotations

from typing import Any

import structlog
from fastapi import APIRouter
from pydantic import BaseModel, Field

from proxym.mcp._helpers import _get_dashboard, _get_orchestrator

router = APIRouter()
logger = structlog.get_logger()

_VM_ID_DESC = "VM identifier"


# ── Request models ────────────────────────────────────────

class VMCreateRequest(BaseModel):
    tool: str = Field(..., description="AI tool: windsurf | cursor | vscode | roocode")
    account: str = Field("", description="Account ID (empty = cheapest active)")
    project: str = Field(..., description="Project name from ~/github/")


class VMActionRequest(BaseModel):
    vm_id: str = Field(..., description=_VM_ID_DESC)


class VMSnapshotRequest(BaseModel):
    vm_id: str = Field(..., description=_VM_ID_DESC)
    name: str = Field("", description="Snapshot name (empty = auto-timestamp)")


class VMSwitchRequest(BaseModel):
    vm_id: str = Field(..., description=_VM_ID_DESC)
    project: str = Field(..., description="New project name")


# ── Endpoints ─────────────────────────────────────────────

@router.post("/tools/vm_list")
async def tool_vm_list() -> dict[str, Any]:
    """List all VMs with their status."""
    try:
        _vms, _ = _get_dashboard()
        vms = _vms().list_vms()
        return {"vms": [v.__dict__ if hasattr(v, "__dict__") else v for v in vms]}
    except Exception as exc:
        logger.warning("self_mcp_vm_list_error", error=str(exc))
        return {"vms": [], "error": str(exc)}


@router.post("/tools/vm_create")
async def tool_vm_create(req: VMCreateRequest) -> dict[str, Any]:
    """Create a new VM with an AI tool."""
    try:
        orch_cls = _get_orchestrator()
        orch = orch_cls()
        result = orch.create_vm(
            tool=req.tool, account=req.account, project=req.project,
        )
        logger.info("self_mcp_vm_created", tool=req.tool, project=req.project)
        return {"status": "created", "vm": result}
    except Exception as exc:
        logger.warning("self_mcp_vm_create_error", error=str(exc))
        return {"status": "error", "error": str(exc)}


@router.post("/tools/vm_start")
async def tool_vm_start(req: VMActionRequest) -> dict[str, Any]:
    """Start a stopped VM."""
    try:
        orch_cls = _get_orchestrator()
        orch = orch_cls()
        orch.start_vm(req.vm_id)
        logger.info("self_mcp_vm_started", vm_id=req.vm_id)
        return {"status": "started", "vm_id": req.vm_id}
    except Exception as exc:
        return {"status": "error", "error": str(exc)}


@router.post("/tools/vm_stop")
async def tool_vm_stop(req: VMActionRequest) -> dict[str, Any]:
    """Stop a running VM."""
    try:
        orch_cls = _get_orchestrator()
        orch = orch_cls()
        orch.stop_vm(req.vm_id)
        logger.info("self_mcp_vm_stopped", vm_id=req.vm_id)
        return {"status": "stopped", "vm_id": req.vm_id}
    except Exception as exc:
        return {"status": "error", "error": str(exc)}


@router.post("/tools/vm_snapshot")
async def tool_vm_snapshot(req: VMSnapshotRequest) -> dict[str, Any]:
    """Create a VM snapshot."""
    try:
        orch_cls = _get_orchestrator()
        orch = orch_cls()
        name = req.name or f"auto-{__import__('time').time():.0f}"
        orch.snapshot_vm(req.vm_id, name)
        return {"status": "snapshot_created", "vm_id": req.vm_id, "name": name}
    except Exception as exc:
        return {"status": "error", "error": str(exc)}


@router.post("/tools/vm_switch_project")
async def tool_vm_switch_project(req: VMSwitchRequest) -> dict[str, Any]:
    """Switch project in a running VM."""
    try:
        orch_cls = _get_orchestrator()
        orch = orch_cls()
        orch.switch_project(req.vm_id, req.project)
        return {"status": "switched", "vm_id": req.vm_id, "project": req.project}
    except Exception as exc:
        return {"status": "error", "error": str(exc)}


# ── Schema fragments ─────────────────────────────────────

TOOL_SCHEMA_VM: list[dict[str, Any]] = [
    {
        "type": "function",
        "function": {
            "name": "vm_list",
            "description": "List all VMs with their current status",
            "parameters": {"type": "object", "properties": {}, "required": []},
        },
    },
    {
        "type": "function",
        "function": {
            "name": "vm_create",
            "description": "Create a new VM with an AI tool",
            "parameters": {
                "type": "object",
                "properties": {
                    "tool": {
                        "type": "string",
                        "enum": ["windsurf", "cursor", "vscode", "roocode"],
                        "description": "AI tool to install in the VM",
                    },
                    "account": {"type": "string", "description": "API account ID"},
                    "project": {"type": "string", "description": "Project name from ~/github/"},
                },
                "required": ["tool", "project"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "vm_start",
            "description": "Start a stopped VM",
            "parameters": {
                "type": "object",
                "properties": {
                    "vm_id": {"type": "string", "description": _VM_ID_DESC},
                },
                "required": ["vm_id"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "vm_stop",
            "description": "Stop a running VM",
            "parameters": {
                "type": "object",
                "properties": {
                    "vm_id": {"type": "string", "description": _VM_ID_DESC},
                },
                "required": ["vm_id"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "vm_snapshot",
            "description": "Create a VM snapshot",
            "parameters": {
                "type": "object",
                "properties": {
                    "vm_id": {"type": "string", "description": _VM_ID_DESC},
                    "name": {"type": "string", "description": "Snapshot name"},
                },
                "required": ["vm_id"],
            },
        },
    },
]
