import type { ToolConfig } from './index'
import { apiFetch } from '@/lib/tauri'

let routerInstance: any = null

export function setRouter(router: any) {
  routerInstance = router
}

export interface ToolManagementCallbacks {
  getRegisteredTools: () => string[]
  getAllToolNames: () => string[]
  activateTool: (name: string) => Promise<boolean>
  deactivateTool: (name: string) => boolean
  togglePin: (name: string) => void
  isToolPinned: (name: string) => boolean
}

export function createGlobalHandlers(callbacks: ToolManagementCallbacks): ToolConfig[] {
  const { getRegisteredTools, getAllToolNames, activateTool, deactivateTool, togglePin, isToolPinned } = callbacks
  const allToolNames = getAllToolNames()
  return [
    {
      name: 'get_current_page',
      description: 'Obtiene la pagina actualmente activa en Agent UI',
      category: 'global',
      schema: {
        type: 'object',
        properties: {}
      },
      handler: () => {
        if (!routerInstance) {
          return 'Error: Router no disponible'
        }

        const route = routerInstance.currentRoute.value
        const pageInfo: Record<string, string> = {
          home: 'Home - Canvas principal con componentes',
          canvas: 'Canvas - Renderiza componentes Vue y HTML',
          components: 'Components - Gestiona componentes guardados',
          themes: 'Themes - Editor visual de temas',
          database: 'Database - Explorador de base de datos',
          source: 'Source - Navegador de codigo fuente',
          terminal: 'Terminal - Consola de comandos',
          tools: 'Tools - Gestion de herramientas MCP',
          agents: 'Agents - Editor de configuracion de agentes Claude Code'
        }

        const pageName = route.name as string || 'unknown'
        const description = pageInfo[pageName] || 'Pagina desconocida'

        return `Pagina actual: ${pageName}\n` +
          `Ruta: ${route.path}\n` +
          `Descripcion: ${description}\n\n` +
          `Herramientas disponibles:\n${getRegisteredTools().map(t => `  - ${t}`).join('\n')}`
      }
    },
    {
      name: 'navigate_to',
      description: 'Navega a una pagina especifica de Agent UI',
      category: 'global',
      schema: {
        type: 'object',
        properties: {
          page: {
            type: 'string',
            enum: ['home', 'canvas', 'components', 'themes', 'database', 'source', 'terminal', 'tools', 'agents'],
            description: 'Pagina a la que navegar'
          }
        },
        required: ['page']
      },
      handler: async (args: { page: string }) => {
        if (!routerInstance) {
          return 'Error: Router no disponible'
        }

        const routes: Record<string, string> = {
          home: '/',
          canvas: '/dynamic/canvas',
          components: '/components',
          themes: '/themes',
          database: '/database',
          source: '/source',
          terminal: '/terminal',
          tools: '/tools',
          agents: '/agents'
        }

        const path = routes[args.page]
        if (!path) {
          return `Error: Pagina "${args.page}" no valida. Opciones: ${Object.keys(routes).join(', ')}`
        }

        try {
          await routerInstance.push(path)
          return `Navegando a ${args.page} (${path})`
        } catch (e: any) {
          return `Error al navegar: ${e.message}`
        }
      }
    },
    {
      name: 'list_available_tools',
      description: 'Lista todas las herramientas MCP actualmente disponibles',
      category: 'global',
      schema: {
        type: 'object',
        properties: {}
      },
      handler: () => {
        const tools = getRegisteredTools()
        if (tools.length === 0) {
          return 'No hay herramientas registradas'
        }
        return `Herramientas MCP disponibles (${tools.length}):\n${tools.map(t => `  - ${t}`).join('\n')}`
      }
    },
    {
      name: 'activate_tool',
      description: 'Activa una herramienta MCP para que este disponible',
      category: 'global',
      schema: {
        type: 'object',
        properties: {
          tool_name: {
            type: 'string',
            enum: allToolNames,
            description: 'Nombre de la herramienta a activar'
          }
        },
        required: ['tool_name']
      },
      handler: async (args: { tool_name: string }) => {
        const activeTools = getRegisteredTools()
        if (activeTools.includes(args.tool_name)) {
          return `La herramienta "${args.tool_name}" ya esta activa`
        }

        const success = await activateTool(args.tool_name)
        if (success) {
          return `Herramienta "${args.tool_name}" activada correctamente`
        } else {
          return `Error: No se pudo activar "${args.tool_name}". Verifica que el nombre sea correcto.`
        }
      }
    },
    {
      name: 'deactivate_tool',
      description: 'Desactiva una herramienta MCP. Si esta pinneada, la despinea primero.',
      category: 'global',
      schema: {
        type: 'object',
        properties: {
          tool_name: {
            type: 'string',
            enum: allToolNames,
            description: 'Nombre de la herramienta a desactivar'
          }
        },
        required: ['tool_name']
      },
      handler: (args: { tool_name: string }) => {
        const activeTools = getRegisteredTools()
        if (!activeTools.includes(args.tool_name)) {
          return `La herramienta "${args.tool_name}" no esta activa`
        }

        // Si esta pinneada, despinear primero
        if (isToolPinned(args.tool_name)) {
          togglePin(args.tool_name)
        }

        const success = deactivateTool(args.tool_name)
        if (success) {
          return `Herramienta "${args.tool_name}" desactivada correctamente`
        } else {
          return `Error: No se pudo desactivar "${args.tool_name}"`
        }
      }
    },
    {
      name: 'pin_tool',
      description: 'Pinnea una herramienta MCP. Las herramientas pinneadas permanecen activas al cambiar de pagina.',
      category: 'global',
      schema: {
        type: 'object',
        properties: {
          tool_name: {
            type: 'string',
            enum: allToolNames,
            description: 'Nombre de la herramienta a pinnear'
          }
        },
        required: ['tool_name']
      },
      handler: async (args: { tool_name: string }) => {
        if (isToolPinned(args.tool_name)) {
          return `La herramienta "${args.tool_name}" ya esta pinneada`
        }

        togglePin(args.tool_name)

        // Asegurar que este activa
        const activeTools = getRegisteredTools()
        if (!activeTools.includes(args.tool_name)) {
          await activateTool(args.tool_name)
        }

        return `Herramienta "${args.tool_name}" pinneada. Permanecera activa al cambiar de pagina.`
      }
    },
    {
      name: 'page_refresh',
      description: 'Recarga la pagina completamente.',
      category: 'global',
      schema: {
        type: 'object',
        properties: {}
      },
      handler: () => {
        setTimeout(() => {
          window.location.reload()
        }, 100)
        return 'Recargando pagina...'
      }
    },
    {
      name: 'whisper_status',
      description: 'Obtiene el estado del servidor Whisper GPU para speech-to-text.',
      category: 'global',
      schema: {
        type: 'object',
        properties: {}
      },
      handler: async () => {
        try {
          const res = await apiFetch('/api/whisper/status')
          const data = await res.json()
          return `Whisper GPU Status:\n` +
            `  Enabled: ${data.enabled ? 'Yes' : 'No'}\n` +
            `  Running: ${data.running ? 'Yes' : 'No'}\n` +
            `  Model: ${data.model}\n` +
            `  Device: ${data.device}\n` +
            `  Port: ${data.port}`
        } catch (e: any) {
          return `Error checking Whisper status: ${e.message}`
        }
      }
    },
    {
      name: 'whisper_toggle',
      description: 'Activa o desactiva Whisper GPU para speech-to-text. Cuando esta activo usa la GPU para transcribir voz con mejor precision para acentos latinos.',
      category: 'global',
      schema: {
        type: 'object',
        properties: {}
      },
      handler: async () => {
        try {
          const res = await apiFetch('/api/whisper/toggle', {
            method: 'POST'
          })
          const data = await res.json()

          if (data.enabled) {
            return `Whisper GPU ENABLED\n` +
              `  Model: ${data.model}\n` +
              `  Device: ${data.device}\n` +
              `  Port: ${data.port}\n\n` +
              `Voice input will now use GPU-accelerated transcription.`
          } else {
            return `Whisper GPU DISABLED\n\n` +
              `Voice input will use Web Speech API (browser native).`
          }
        } catch (e: any) {
          return `Error toggling Whisper: ${e.message}`
        }
      }
    },
    {
      name: 'whisper_start',
      description: 'Inicia el servidor Whisper GPU si no esta corriendo.',
      category: 'global',
      schema: {
        type: 'object',
        properties: {}
      },
      handler: async () => {
        try {
          const res = await apiFetch('/api/whisper/start', {
            method: 'POST'
          })
          const data = await res.json()

          if (data.success) {
            return `Whisper server started!\n` +
              `  Model: ${data.model}\n` +
              `  Device: ${data.device}\n` +
              `  Ready: ${data.running ? 'Yes' : 'Loading...'}`
          } else {
            return `Failed to start Whisper server: ${data.message}`
          }
        } catch (e: any) {
          return `Error starting Whisper: ${e.message}`
        }
      }
    },
    {
      name: 'whisper_stop',
      description: 'Detiene el servidor Whisper GPU para liberar memoria de la GPU.',
      category: 'global',
      schema: {
        type: 'object',
        properties: {}
      },
      handler: async () => {
        try {
          const res = await apiFetch('/api/whisper/stop', {
            method: 'POST'
          })
          const data = await res.json()

          if (data.success) {
            return `Whisper server stopped. GPU memory released.`
          } else {
            return `Failed to stop Whisper server: ${data.message}`
          }
        } catch (e: any) {
          return `Error stopping Whisper: ${e.message}`
        }
      }
    }
  ]
}
