import type { Router, RouteRecordRaw } from 'vue-router'
import type { Tool } from '@/shared/stores/tools'


const toolComponents = import.meta.glob('@/views/tools/**/*.vue', { eager: false })

function snakeToPascal(snakeStr: string): string {
  const components = snakeStr.split('_')
  return components.map(word => word.charAt(0).toUpperCase() + word.slice(1)).join('')
}

function generateRouteName(toolName: string): string {
  return snakeToPascal(toolName)
}

function generateRoutePath(toolName: string): string {
  const pathName = toolName.replace(/_/g, '-')
  return `tools/${pathName}`
}

export function ensureToolRoutes(tool: Tool): Tool {
  const routeNameBase = tool.toolName || tool.marketplaceId || tool.name || tool.id
  const routePathBase = tool.toolName || tool.marketplaceId || tool.name || tool.id
  
  if (!tool.routeName) {
    tool.routeName = generateRouteName(routeNameBase)
  }
  
  if (!tool.routePath) {
    tool.routePath = generateRoutePath(routePathBase)
  }
  
  return tool
}
export function registerToolRoute(
  router: Router,
  tool: Tool,
  componentPath?: string
): boolean {
  const toolWithRoutes = ensureToolRoutes({ ...tool })
  
  if (!toolWithRoutes.routeName) {
    return false
  }

  if (router.hasRoute(toolWithRoutes.routeName)) {
    return false
  }

  // 构建组件路径（使用别名路径，Vite 会在构建时正确处理）
  let finalComponentPath: string
  if (componentPath) {
    finalComponentPath = componentPath.startsWith('@/') ? componentPath : `@/views/${componentPath}`
  } else if (toolWithRoutes.componentPath) {
    finalComponentPath = toolWithRoutes.componentPath.startsWith('@/') ? toolWithRoutes.componentPath : `@/views/${toolWithRoutes.componentPath}`
  } else {
    const toolDirName = toolWithRoutes.toolName || toolWithRoutes.id
    finalComponentPath = `@/views/tools/${toolDirName}/${toolDirName}.vue`
  }
  
  const routePath = toolWithRoutes.routePath || (() => {
    const toolDirName = toolWithRoutes.toolName || toolWithRoutes.id
    return `tools/${toolDirName.replace(/_/g, '-')}`
  })()

  const route: RouteRecordRaw = {
    path: routePath,
    name: toolWithRoutes.routeName,
    component: () => {
      const normalizedPath = finalComponentPath.replace(/^@\//, '/src/')
      const componentLoader = toolComponents[normalizedPath]
      
      if (!componentLoader) {
        console.error(`Tool component not found in glob: ${finalComponentPath} (normalized: ${normalizedPath})`)
        return Promise.resolve({
          name: 'ToolComponentError',
          template: `
            <div style="padding: 20px; text-align: center;">
              <h3>Component Not Found</h3>
              <p>Failed to load component: ${finalComponentPath}</p>
              <p style="color: #666; font-size: 12px; margin-top: 10px;">The component is not registered in the tool components glob.</p>
            </div>
          `
        })
      }
      
      return componentLoader().catch((error) => {
        console.error(`Failed to load tool component: ${finalComponentPath}`, error)
        return {
          name: 'ToolComponentError',
          template: `
            <div style="padding: 20px; text-align: center;">
              <h3>Component Not Found</h3>
              <p>Failed to load component: ${finalComponentPath}</p>
              <p style="color: #666; font-size: 12px; margin-top: 10px;">Error: ${error.message || error}</p>
            </div>
          `
        }
      })
    },
    meta: {
      requiresAuth: true,
      toolId: toolWithRoutes.id,
      toolName: toolWithRoutes.name
    }
  }

  try {
    router.addRoute('AppLayout', route)
    return true
  } catch (error) {
    console.error(`Failed to register tool route ${toolWithRoutes.routeName}:`, error)
    return false
  }
}

export function unregisterToolRoute(router: Router, routeName: string): boolean {
  if (!router.hasRoute(routeName)) {
    return false
  }

  try {
    router.removeRoute(routeName)
    return true
  } catch (error) {
    console.error(`Failed to remove tool route ${routeName}:`, error)
    return false
  }
}

export function registerAllToolRoutes(router: Router, tools: Tool[]): void {
  tools.forEach(tool => {
    registerToolRoute(router, tool, tool.componentPath)
  })
}

