"""Proxym Tools — manage proxym from Open WebUI chat.

Upload this file in Open WebUI → Settings → Tools → Add Tool.
It registers proxym management functions as callable tools for the LLM.
"""

import httpx
from pydantic import BaseModel

PROXYM_BASE = "http://localhost:4000"
PROXYM_KEY = "sk-proxym-master-changeme"


def _call(method: str, path: str, **kwargs) -> dict:
    with httpx.Client(
        base_url=PROXYM_BASE,
        headers={"Authorization": f"Bearer {PROXYM_KEY}"},
        timeout=10,
    ) as c:
        fn = getattr(c, method.lower())
        return fn(path, **kwargs).json()


class ProxymTools:
    """Tools for managing proxym AI proxy from Open WebUI."""

    def get_status(self) -> str:
        """
        Get full system status: proxy, VMs, accounts, daily costs.
        :return: System status as JSON string
        """
        return str(_call("GET", "/api/v1/system/status"))

    def list_vms(self) -> str:
        """
        List all virtual machines (VMs) with their status.
        :return: VM list with fields: vm_id, tool, state, project, account
        """
        return str(_call("GET", "/api/v1/vms"))

    def create_vm(self, tool: str, project: str, account: str = "") -> str:
        """
        Create a new VM with an AI tool.
        :param tool: AI tool: windsurf, cursor, vscode, or roocode
        :param project: Project name from ~/github/
        :param account: (optional) API account ID; empty = cheapest active
        :return: Created VM status
        """
        return str(_call("POST", "/api/v1/vms", json={
            "tool": tool, "project": project, "account": account,
        }))

    def start_vm(self, vm_id: str) -> str:
        """
        Start a stopped VM.
        :param vm_id: VM identifier (e.g. windsurf-work)
        :return: Operation status
        """
        return str(_call("POST", f"/api/v1/vms/{vm_id}/start"))

    def stop_vm(self, vm_id: str) -> str:
        """
        Stop a running VM.
        :param vm_id: VM identifier
        :return: Operation status
        """
        return str(_call("POST", f"/api/v1/vms/{vm_id}/stop"))

    def get_costs(self) -> str:
        """
        Get cost summary: daily, monthly, per account, per model.
        :return: Cost summary
        """
        return str(_call("GET", "/api/v1/dashboard/costs/summary"))

    def get_logs(self, lines: int = 50, level: str = "all") -> str:
        """
        Get recent proxym logs.
        :param lines: Number of log lines (default 50)
        :param level: Log level: all, error, warn, info
        :return: Recent logs
        """
        return str(_call("GET", f"/api/v1/logs?lines={lines}&level={level}"))

    def list_models(self) -> str:
        """
        List available AI models with prices and aliases.
        :return: Model list
        """
        return str(_call("GET", "/v1/models"))
