import { createRouter, createWebHistory } from 'vue-router'
import Dashboard from '@/views/Dashboard.vue'
import Login from '@/views/Login.vue'
import Signup from '@/views/Signup.vue'
import Chat from '@/views/Chat.vue'
import Agents from '@/views/Agents.vue'
import Team from '@/views/Team.vue'
import Skill from '@/views/Skill.vue'
import Tools from '@/views/Tools.vue'
import Database from '@/views/Database.vue'
import Script from '@/views/Script.vue'
import Plan from '@/views/Plan.vue'
import Memory from '@/views/Memory.vue'
import Knowledge from '@/views/Knowledge.vue'
import Settings from '@/views/Settings.vue'
import Account from '@/views/Account.vue'
import Logs from '@/views/Logs.vue'

// 需要登录才能访问的路由
const protectedRoutes = ['/dashboard', '/chat', '/agents', '/team', '/mcp', '/tools', '/database', '/script', '/plan', '/memory', '/knowledge', '/settings', '/account', '/logs']

// 检查是否已登录
const isAuthenticated = () => {
  return !!localStorage.getItem('token')
}

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: () => isAuthenticated() ? '/dashboard' : '/login'
    },
    {
      path: '/login',
      name: 'login',
      component: Login
    },
    {
      path: '/signup',
      name: 'signup',
      component: Signup
    },
    {
      path: '/dashboard',
      name: 'dashboard',
      component: Dashboard
    },
    {
      path: '/chat',
      name: 'chat',
      component: Chat
    },
    {
      path: '/agents',
      name: 'agents',
      component: Agents
    },
    {
      path: '/team',
      name: 'team',
      component: Team
    },
    {
      path: '/mcp',
      name: 'mcp',
      component: Skill
    },
    {
      path: '/tools',
      name: 'tools',
      component: Tools
    },
    {
      path: '/database',
      name: 'database',
      component: Database
    },
    {
      path: '/script',
      name: 'script',
      component: Script
    },
    {
      path: '/plan',
      name: 'plan',
      component: Plan
    },
    {
      path: '/memory',
      name: 'memory',
      component: Memory
    },
    {
      path: '/knowledge',
      name: 'knowledge',
      component: Knowledge
    },
    {
      path: '/settings',
      name: 'settings',
      component: Settings
    },
    {
      path: '/account',
      name: 'account',
      component: Account
    },
    {
      path: '/logs',
      name: 'logs',
      component: Logs
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const isAuth = isAuthenticated()
  const isLoginPage = to.path === '/login' || to.path === '/signup'

  // 如果未登录且不是访问登录/注册页，跳转到登录页
  if (!isAuth && !isLoginPage) {
    next('/login')
    return
  }

  // 如果已登录且访问登录/注册页，跳转到仪表盘
  if (isAuth && isLoginPage) {
    next('/dashboard')
    return
  }

  next()
})

export default router
