import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const routes: RouteRecordRaw[] = [
  // Login (public)
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/LoginView.vue'),
    meta: { title: '登录', public: true },
  },

  // Agent-First 左对话+右双栏布局
  {
    path: '/agent',
    name: 'agent',
    component: () => import('@/components/layout/AgentLayout.vue'),
    meta: { title: 'AgentKit' },
    children: [
      {
        path: '',
        redirect: '/agent/chat',
      },
      {
        path: 'chat',
        name: 'agent-chat',
        meta: { title: '对话', panel: 'left' },
        component: () => import('@/views/ChatView.vue'),
      },
      {
        path: 'code',
        name: 'agent-code',
        meta: { title: '代码', panel: 'tr', tab: 'code' },
        component: () => import('@/views/WorkflowView.vue'),
      },
      {
        path: 'monitor',
        name: 'agent-monitor',
        meta: { title: '监控', panel: 'br', tab: 'monitor' },
        component: () => import('@/views/EvolutionView.vue'),
      },
      {
        path: 'preview',
        name: 'agent-preview',
        meta: { title: 'VI Mockup Preview', panel: 'left' },
        component: () => import('@/views/ChatPreviewView.vue'),
      },
    ],
  },

  // Default redirect to agent layout
  {
    path: '/',
    redirect: '/agent',
  },

  // Legacy route redirects → agent quadrant routes
  {
    path: '/workflow',
    redirect: '/agent/code?tab=workflow',
  },
  {
    path: '/knowledge',
    redirect: '/agent/code?tab=knowledge',
  },
  {
    path: '/skills',
    redirect: '/agent/monitor?tab=skills',
  },
  {
    path: '/evolution',
    redirect: '/agent/monitor?tab=monitor',
  },
  {
    path: '/settings',
    redirect: '/agent/monitor?tab=settings',
  },
  {
    path: '/terminal',
    redirect: '/legacy/terminal',
  },

  // Computer Use (保留独立路由，显示"即将推出")
  {
    path: '/computer-use',
    name: 'computer-use',
    component: () => import('@/views/ComputerUseView.vue'),
    meta: { title: 'Computer Use' },
  },

  // Bitable 多维表格 (独立全屏视图，三层路由：文件列表 → 文件详情 → 表详情)
  {
    path: '/bitable',
    name: 'bitable',
    meta: { title: '多维表格' },
    children: [
      {
        path: '',
        name: 'bitable-file-list',
        component: () => import('@/views/BitableFileListView.vue'),
        meta: { title: '多维表格' },
      },
      {
        path: ':fileId',
        name: 'bitable-file-detail',
        component: () => import('@/views/BitableFileDetailView.vue'),
        meta: { title: '多维表格' },
      },
      {
        path: ':fileId/:tableId',
        name: 'bitable-table-detail',
        component: () => import('@/views/BitableFileDetailView.vue'),
        meta: { title: '多维表格' },
      },
    ],
  },

  // Admin console (U9) — AdminLayout wraps all /admin/* child routes.
  // ``requiresAdmin`` is set on the parent so the guard checks it for
  // every child route (Vue Router merges parent meta into matched records).
  {
    path: '/admin',
    name: 'admin',
    component: () => import('@/components/layout/AdminLayout.vue'),
    meta: { title: '管理控制台', requiresAdmin: true },
    redirect: '/admin/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'admin-dashboard',
        component: () => import('@/views/admin/DashboardView.vue'),
        meta: { title: '管理概览', requiresAdmin: true },
      },
      {
        path: 'departments',
        name: 'admin-departments',
        component: () => import('@/views/admin/DepartmentsView.vue'),
        meta: { title: '部门管理', requiresAdmin: true },
      },
      {
        path: 'users',
        name: 'admin-users',
        component: () => import('@/views/admin/UsersView.vue'),
        meta: { title: '用户与会话管理', requiresAdmin: true },
      },
      {
        path: 'llm',
        name: 'admin-llm',
        component: () => import('@/views/admin/LlmConfigView.vue'),
        meta: { title: 'LLM 配置', requiresAdmin: true },
      },
      {
        path: 'skills',
        name: 'admin-skills',
        component: () => import('@/views/admin/SkillsView.vue'),
        meta: { title: 'Skill 管理', requiresAdmin: true },
      },
      {
        path: 'kb',
        name: 'admin-kb',
        component: () => import('@/views/admin/KbManagementView.vue'),
        meta: { title: '知识库管理', requiresAdmin: true },
      },
      {
        path: 'usage',
        name: 'admin-usage',
        component: () => import('@/views/admin/UsageDashboardView.vue'),
        meta: { title: '用量仪表盘', requiresAdmin: true },
      },
    ],
  },

  // Legacy layout (fallback)
  {
    path: '/legacy',
    name: 'legacy',
    component: () => import('@/components/layout/AppLayout.vue'),
    meta: { title: 'Fischer AgentKit (Legacy)' },
    children: [
      {
        path: '',
        redirect: '/legacy/chat',
      },
      {
        path: 'chat',
        name: 'legacy-chat',
        component: () => import('@/views/ChatView.vue'),
        meta: { title: '智能对话' },
      },
      {
        path: 'workflow',
        name: 'legacy-workflow',
        component: () => import('@/views/WorkflowView.vue'),
        meta: { title: '工作流' },
      },
      {
        path: 'knowledge',
        name: 'legacy-knowledge',
        component: () => import('@/views/KnowledgeBaseView.vue'),
        meta: { title: '知识库' },
      },
      {
        path: 'skills',
        name: 'legacy-skills',
        component: () => import('@/views/SkillsView.vue'),
        meta: { title: '技能' },
      },
      {
        path: 'terminal',
        name: 'legacy-terminal',
        component: () => import('@/views/TerminalView.vue'),
        meta: { title: '终端' },
      },
      {
        path: 'evolution',
        name: 'legacy-evolution',
        component: () => import('@/views/EvolutionView.vue'),
        meta: { title: '自进化' },
      },
      {
        path: 'settings',
        name: 'legacy-settings',
        component: () => import('@/views/SettingsView.vue'),
        meta: { title: '设置' },
      },
    ],
  },
]

const router = createRouter({
  history: createWebHistory(),
  routes,
})

/**
 * Global route guard.
 *
 * - Public routes (meta.public === true) are always allowed.
 * - Non-public routes require an authenticated user; unauthenticated
 *   users are redirected to /login with a ``redirect`` query param
 *   preserving the original target.
 *
 * CRITICAL: ``router.beforeEach`` runs BEFORE ``App.vue::onMounted``.
 * On a Tauri reload the access token is gone (memory-only) and
 * ``startupState`` is still ``'pending'`` because ``startupCheck()``
 * hasn't run yet. Without waiting, the guard would see
 * ``isAuthenticated === false`` and bounce every reload to /login.
 *
 * We therefore ``await authStore.waitForStartup()`` when the state is
 * still pending. The cold-start is kicked off in ``main.ts`` before
 * ``app.mount()`` so the promise is already in flight by the time the
 * first navigation resolves.
 *
 * Startup states after the await:
 *  - 'valid'   → authenticated, allow
 *  - 'invalid' → not authenticated, redirect to /login
 *  - 'error'   → backend unreachable / health check failed; allow the
 *                navigation through so ``App.vue``'s SplashScreen can
 *                surface the error + retry button (the splash overlays
 *                ``<router-view>`` so no protected content leaks).
 */
router.beforeEach(async (to, _from, next) => {
  const title = to.meta.title as string | undefined
  if (title) {
    document.title = `${title} - Fischer AgentKit`
  }

  const isPublic = to.meta.public === true
  if (isPublic) {
    next()
    return
  }

  const authStore = useAuthStore()
  // Wait for the cold-start probe (Tauri bootstrap + whoami) to finish
  // before making any routing decision.
  if (authStore.startupState === 'pending') {
    await authStore.waitForStartup()
  }

  // Backend error — let App.vue's SplashScreen show the retry UI.
  if (authStore.startupState === 'error') {
    next()
    return
  }

  if (!authStore.isAuthenticated) {
    // Preserve the original target so we can redirect after login
    next({
      name: 'login',
      query: { redirect: to.fullPath },
    })
    return
  }

  // Admin-only routes require the admin role.
  if (to.meta.requiresAdmin === true && !authStore.isAdmin()) {
    next({ name: 'agent-chat' })
    return
  }

  next()
})

export default router
