import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '../../shared/stores/auth'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: () => import('../../views/auth/Login.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/signup',
      name: 'Signup',
      component: () => import('../../views/auth/Signup.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/setup-wizard',
      name: 'SetupWizard',
      component: () => import('../../views/auth/SetupWizard.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/',
      name: 'AppLayout',
      component: () => import('../layouts/AppLayout.vue'),
      meta: { requiresAuth: true },
      children: [
        {
          path: '',
          name: 'Root',
          redirect: '/app'
        },
        {
          path: 'app',
          name: 'App',
          component: () => import('../../views/Dashboard.vue')
        },
        {
          path: 'dashboard',
          name: 'Dashboard',
          component: () => import('../../views/Dashboard.vue')
        },
        {
          path: 'local-jobs',
          name: 'LocalJobList',
          component: () => import('../../views/localJobs/LocalJobList.vue')
        },
        {
          path: 'local-jobs/:id',
          name: 'LocalJobDetail',
          // @ts-ignore
          component: () => import('../../views/localJobs/LocalJobDetail.vue')
        },
        {
          path: 'flows',
          name: 'FlowBuilder',
          component: () => import('../../views/flows/FlowBuilder.vue')
        },
        {
          path: 'scheduled-jobs',
          name: 'ScheduledJobList',
          component: () => import('../../views/scheduledJobs/ScheduledJobList.vue')
        },
        {
          path: 'scheduled-jobs/:id',
          name: 'ScheduledJobDetail',
          component: () => import('../../views/scheduledJobs/ScheduledJobDetail.vue')
        },
        {
          path: 'permission-manager',
          name: 'RolePermissionManager',
          component: () => import('../../views/permissions/RolePermissionManager.vue'),
          meta: { requiresAuth: true }
        },
        // Workspace 页面
        {
          path: 'workspace/:name',
          name: 'WorkspacePage',
          component: () => import('../../views/workspace/WorkspacePage.vue')
        },
        // Private Workspace 页面
        {
          path: 'workspace/private/:name',
          name: 'PrivateWorkspacePage',
          component: () => import('../../views/workspace/WorkspacePage.vue')
        },
        // Query Report 页面
        {
          path: 'app/query-report/:reportName?',
          name: 'QueryReport',
          component: () => import('../../views/QueryReport.vue')
        },
        // MindMap 编辑器（新版四层架构）
        {
          path: 'mindmap',
          name: 'MindMapEditor',
          component: () => import('../../core/features/mindmap/MindMapEditor.vue'),
          meta: { title: 'Mind Map Editor' }
        },
        // Whiteboard 编辑器（自研Canvas架构）
        {
          path: 'whiteboard',
          name: 'WhiteboardEditor',
          component: () => import('../../core/features/whiteboard/WhiteboardEditor.vue'),
          meta: { title: 'Whiteboard Editor' }
        },
        // 页面类型 pagetype 列表/详情 - 支持多种格式
        {
          path: 'app/:entity',
          name: 'PageTypeList',
          component: () => import('./listPage')
        },
        {
          path: 'app/:entity/:id',
          name: 'PageTypeDetail',
          component: () => import('./detailPage')
        },
        // 保持向后兼容
        {
          path: 'page/:entity',
          name: 'PageTypeListLegacy',
          component: () => import('./listPage')
        },
        {
          path: 'page/:entity/:id',
          name: 'PageTypeDetailLegacy',
          component: () => import('./detailPage')
        },
        {
          path: 'tools',
          name: 'Tools',
          component: () => import('../../views/Tools.vue')
        },
        {
          path: 'search',
          name: 'SearchResults',
          component: () => import('../../views/SearchResults.vue')
        },
        // 开发
        {
          path: 'dev/create-pagetype-template',
          name: 'CreatePagetypeTemplate',
          component: () => import('../../views/dev/CreatePagetypeTemplate.vue')
        },
        {
          path: 'dev/create-app-template',
          name: 'CreateAppTemplate',
          component: () => import('../../views/dev/CreateAppTemplate.vue')
        },
        {
          path: 'app-installer',
          name: 'AppInstaller',
          component: () => import('../../views/dev/AppInstaller.vue')
        },
        {
          path: 'installed-apps',
          name: 'InstalledApps',
          component: () => import('../../views/dev/InstalledApps.vue')
        },
        {
          path: 'app-marketplace',
          name: 'AppMarketplace',
          component: () => import('../../views/dev/AppMarketplace.vue')
        },
        {
          path: 'node-marketplace',
          name: 'NodeMarketplace',
          component: () => import('../../views/dev/NodeMarketplace.vue')
        },
        {
          path: 'node-marketplace/:name',
          name: 'NodeDetail',
          component: () => import('../../views/dev/NodeDetail.vue')
        },
        {
          path: 'agent-marketplace',
          name: 'AgentMarketplace',
          component: () => import('../../views/dev/AgentMarketplace.vue')
        },
        {
          path: 'agent-marketplace/:name',
          name: 'AgentDetail',
          component: () => import('../../views/dev/AgentDetail.vue')
        },
        {
          path: 'tool-marketplace',
          name: 'ToolMarketplace',
          component: () => import('../../views/dev/ToolMarketplace.vue')
        },
        {
          path: 'tool-marketplace/:name',
          name: 'ToolDetail',
          component: () => import('../../views/dev/ToolDetail.vue')
        },
        {
          path: 'publish-tool',
          name: 'PublishTool',
          component: () => import('../../views/dev/PublishTool.vue'),
          meta: { requiresAuth: true }
        },
        {
          path: 'app-marketplace/:name',
          name: 'AppDetail',
          component: () => import('../../views/dev/AppDetail.vue')
        },
        {
          path: 'publish-app',
          name: 'PublishApp',
          component: () => import('../../views/dev/PublishApp.vue'),
          meta: { requiresAuth: true }
        },
        {
          path: 'my-published-apps',
          name: 'MyPublishedApps',
          component: () => import('../../views/dev/MyPublishedApps.vue'),
          meta: { requiresAuth: true }
        },
        {
          path: 'my-published-nodes',
          name: 'MyPublishedNodes',
          component: () => import('../../views/dev/MyPublishedNodes.vue'),
          meta: { requiresAuth: true }
        },
        {
          path: 'my-published-agents',
          name: 'MyPublishedAgents',
          component: () => import('../../views/dev/MyPublishedAgents.vue'),
          meta: { requiresAuth: true }
        },
        {
          path: 'my-published-tools',
          name: 'MyPublishedTools',
          component: () => import('../../views/dev/MyPublishedTools.vue'),
          meta: { requiresAuth: true }
        }
      ]
    }
  ]
})

router.beforeEach(async (to, _from, next) => {
  // 检测预渲染环境
  const isPrerendering = typeof window !== 'undefined' && navigator.userAgent.includes('HeadlessChrome')
  
  const authStore = useAuthStore()
  
  if (!authStore.isAuthenticated) {
    await authStore.initAuth()
  }
  
  // Prerender bypass
  if (isPrerendering) {
    next()
    return
  }
  
  // Auth check: redirect to login if not authenticated
  if (to.meta.requiresAuth && !authStore.isLoggedIn) {
    next('/login')
    return
  }
  
  // Redirect logged-in users away from login/signup
  if ((to.path === '/login' || to.path === '/signup') && authStore.isLoggedIn) {
    next('/')
    return
  }
  
  // Check setup wizard completion status - only for Administrator user
  if (authStore.isLoggedIn && authStore.user?.name === 'Administrator') {
    const setupComplete = (window as any).jingrow?.boot?.setup_complete
    
    // If setup is complete, redirect away from setup-wizard
    if (to.path === '/setup-wizard' && setupComplete) {
      next('/')
      return
    }
    
    // If setup is not complete, redirect to setup wizard
    if (to.path !== '/setup-wizard' && !setupComplete) {
      next('/setup-wizard')
      return
    }
  }
  
  // Dynamic tool routes
  if (to.path.startsWith('/tools/') && to.name !== 'Tools') {
    // 如果路由已经匹配，直接通过
    if (to.matched.length > 0) {
      // 路由已匹配，继续正常流程
    } else {
      // 尝试解析路由，检查是否存在
      let routeExists = false
      try {
        const resolved = router.resolve(to.path)
        // 如果解析成功且路径匹配，说明路由存在
        routeExists = resolved.matched.length > 0 && resolved.path === to.path
      } catch {
        // 解析失败，说明路由不存在
        routeExists = false
      }
      
      // 如果路由不存在，尝试初始化工具路由
      if (!routeExists) {
        const { useToolsStore } = await import('../../shared/stores/tools')
        const toolsStore = useToolsStore()
        toolsStore.initToolRoutes(router)
        
        // 再次尝试解析路由
        let routeExistsAfter = false
        try {
          const resolvedAfter = router.resolve(to.path)
          routeExistsAfter = resolvedAfter.matched.length > 0 && resolvedAfter.path === to.path
        } catch {
          routeExistsAfter = false
        }
        
        if (routeExistsAfter) {
          // 路由已注册，重新导航到目标路由
          next({ ...to, replace: true })
          return
        } else {
          // 路由不存在，重定向到工具列表页
          next({ name: 'Tools' })
          return
        }
      }
    }
  }
  
  next()
})

export default router
