import type { RouteLocationNormalizedLoaded } from 'vue-router'
import type {
  MissionControlContext,
  MissionControlEntityType,
} from '../types/mission-control'

const ROUTE_SURFACES: Record<string, string> = {
  Dashboard: 'Dashboard',
  Memory: 'Memory',
  Docs: 'Docs',
  AgentDetail: 'Agent detail',
  AgentCreate: 'Agent proposal creation',
  AgentProposalDetail: 'Agent proposal detail',
  Agents: 'Agents',
  Security: 'Security',
  Incidents: 'Incidents',
  Calendar: 'Calendar',
  Projects: 'Projects',
  ProjectDetail: 'Project detail',
  'Task Board': 'Task Board',
  TaskDetail: 'Task detail',
  'Run Control': 'Run Control',
  RunDetail: 'Run detail',
  Models: 'Models',
  Activity: 'Activity',
  Notifications: 'Notifications',
  Settings: 'Settings',
}

const DETAIL_ROUTE_TYPES: Record<string, MissionControlEntityType> = {
  AgentDetail: 'agent',
  AgentProposalDetail: 'agent-proposal',
  ProjectDetail: 'project',
  TaskDetail: 'task',
  RunDetail: 'run',
}

export function buildMissionControlContext(
  route: Pick<RouteLocationNormalizedLoaded, 'name' | 'path' | 'params'>,
): MissionControlContext {
  const routeName = String(route.name ?? 'Unknown')
  const rawId = routeName === 'AgentProposalDetail'
    ? route.params.proposalId
    : route.params.id
  const entityId = Array.isArray(rawId) ? rawId[0] : rawId

  return {
    routeName,
    path: route.path,
    surface: ROUTE_SURFACES[routeName] ?? routeName,
    entityType: DETAIL_ROUTE_TYPES[routeName] ?? null,
    entityId: typeof entityId === 'string' && entityId.trim() ? entityId.trim() : null,
  }
}
