import type { TerminalRouteRecord } from '@simon_he/vue-tui'
import { createTerminalRouter } from '@simon_he/vue-tui'
import { DimSdkChatPage } from './pages/ChatPage'
import { DimSdkHomePage } from './pages/HomePage'

export const dimsdkCliRoutes: TerminalRouteRecord[] = [
  { name: 'home', component: DimSdkHomePage },
  { name: 'chat', component: DimSdkChatPage },
]

function routeName(to: unknown): string {
  if (typeof to === 'string') return to
  if (to != null && typeof to === 'object' && 'name' in to)
    return String(to.name ?? '')
  return ''
}

function pickInitialRoute(
  routes: readonly TerminalRouteRecord[],
  initialRoute: unknown,
): string {
  const n = routeName(initialRoute) || 'home'
  return routes.some((r) => r.name === n) ? n : 'home'
}

export function createDimSdkRouter(
  opts?: Readonly<{ initialRoute?: string; mode?: 'full' | 'cli' }>,
) {
  return createTerminalRouter({
    routes: dimsdkCliRoutes,
    initialRoute: pickInitialRoute(
      dimsdkCliRoutes,
      opts?.initialRoute ?? 'home',
    ),
  })
}
