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

const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/auth/LoginView.vue'),
  },
  {
    path: '/',
    name: 'home',
    component: () => import('@/views/HomeView.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/projects',
    name: 'project-list',
    component: () => import('@/views/projects/ProjectListView.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/p/:slug',
    name: 'project-home',
    component: () => import('@/views/projects/ProjectHomeView.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/p/:slug/requirements',
    name: 'requirement-list',
    component: () => import('@/views/projects/RequirementListView.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/p/:slug/requirements/:number',
    name: 'requirement-detail',
    component: () => import('@/views/projects/RequirementDetailView.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/p/:slug/issues',
    name: 'issue-list',
    component: () => import('@/views/projects/IssueListView.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/p/:slug/issues/:number',
    name: 'issue-detail',
    component: () => import('@/views/projects/IssueDetailView.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/p/:slug/workspaces',
    name: 'workspace-list',
    component: () => import('@/views/workspaces/WorkspaceListView.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/p/:slug/w/:wsSlug',
    name: 'workspace-home',
    component: () => import('@/views/workspaces/WorkspaceHomeView.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/p/:slug/w/:wsSlug/acp-sessions',
    name: 'acp-sessions-list',
    component: () => import('@/views/acp/AcpSessionListView.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/p/:slug/w/:wsSlug/acp-sessions/new',
    name: 'acp-sessions-new',
    component: () => import('@/views/acp/AcpSessionCreateView.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/p/:slug/w/:wsSlug/acp-sessions/:sessionId',
    name: 'acp-sessions-detail',
    component: () => import('@/views/acp/AcpSessionDetailView.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/chat',
    name: 'chat-home',
    component: () => import('@/views/chat/ChatHomeView.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/chat/:conversationId',
    name: 'chat-detail',
    component: () => import('@/views/chat/ChatDetailView.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/projects/:pid/chat',
    name: 'project-chat-home',
    component: () => import('@/views/chat/ChatHomeView.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/projects/:pid/chat/:conversationId',
    name: 'project-chat-detail',
    component: () => import('@/views/chat/ChatDetailView.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/prompt-templates',
    name: 'prompt-templates',
    component: () => import('@/views/prompt-templates/PromptTemplatesView.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/me/usage',
    name: 'me-usage',
    component: () => import('@/views/admin/UsageView.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/me/change-password',
    name: 'me-change-password',
    component: () => import('@/views/ChangePasswordView.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/admin/users',
    name: 'admin-users',
    component: () => import('@/views/admin/UserListView.vue'),
    meta: { requiresAuth: true, requiresAdmin: true },
  },
  {
    path: '/admin/llm-endpoints',
    name: 'admin-llm-endpoints',
    component: () => import('@/views/admin/LLMEndpointsView.vue'),
    meta: { requiresAuth: true, requiresAdmin: true },
  },
  {
    path: '/admin/llm-models',
    name: 'admin-llm-models',
    component: () => import('@/views/admin/LLMModelsView.vue'),
    meta: { requiresAuth: true, requiresAdmin: true },
  },
  {
    path: '/admin/usage',
    name: 'admin-usage',
    component: () => import('@/views/admin/UsageView.vue'),
    props: { adminMode: true },
    meta: { requiresAuth: true, requiresAdmin: true },
  },
  {
    path: '/admin/mcp-tokens',
    name: 'admin-mcp-tokens',
    component: () => import('@/views/admin/MCPTokenAdminView.vue'),
    meta: { requiresAuth: true, requiresAdmin: true },
  },
  {
    path: '/admin/acp-sessions',
    name: 'admin-acp-sessions',
    component: () => import('@/views/acp/AcpAdminSessionsView.vue'),
    meta: { requiresAuth: true, requiresAdmin: true },
  },
  {
    path: '/admin/acp/agent-kinds',
    name: 'admin-acp-agent-kinds',
    component: () => import('@/views/admin/AgentKindAdminListView.vue'),
    meta: { requiresAuth: true, requiresAdmin: true },
  },
  {
    path: '/admin/acp/agent-kinds/new',
    component: () => import('@/views/admin/AgentKindEditView.vue'),
    meta: { requiresAuth: true, requiresAdmin: true },
  },
  {
    path: '/admin/acp/agent-kinds/:id',
    component: () => import('@/views/admin/AgentKindEditView.vue'),
    meta: { requiresAuth: true, requiresAdmin: true },
  },
  {
    path: '/admin/terminal',
    name: 'admin-terminal',
    component: () => import('@/views/admin/AdminTerminalView.vue'),
    meta: { requiresAuth: true, requiresAdmin: true },
  },
  {
    // 兜底：匹配不到的路径（如空参数的 /p/x/w/、手输错误 URL）统一回首页，避免白屏
    path: '/:pathMatch(.*)*',
    redirect: '/',
  },
]

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

router.beforeEach((to) => {
  const auth = useAuthStore()
  if (to.meta.requiresAuth && !auth.isAuthenticated) {
    return { name: 'login', query: { next: to.fullPath } }
  }
  if (to.meta.requiresAdmin && !auth.isAdmin) {
    return { name: 'home' }
  }
  if (to.name === 'login' && auth.isAuthenticated) {
    return { name: 'home' }
  }
  return true
})

export default router

// 把 auth store 注入 api client（在 router 模块顶层晚于 pinia 安装可能未就绪，所以用懒访问）
export function bindAuthToApi() {
  const auth = useAuthStore()
  const redirectToLogin = () => {
    auth.clearSession()
    const current = router.currentRoute.value
    const query = current.name === 'login' ? undefined : { next: current.fullPath }
    router.replace({ name: 'login', query }).catch(() => {})
  }
  configure({
    tokenProvider: () => auth.token,
    onUnauthorized: redirectToLogin,
    // 403：会话仍有效但权限不足（如被降级/禁用），同样登出并回登录页。
    onForbidden: redirectToLogin,
  })
}
