import { apiRoute } from '@/lib/api/handler'
import { getNeighbourhood, loadKnowledgeGraph, search } from '@/lib/services/knowledge-service'

export const dynamic = 'force-dynamic'

/**
 * The knowledge graph (§16, §17).
 *
 * Three modes on one route because they are three views of one structure: a search, a
 * neighbourhood around a node, and the concept-and-region overview.
 */
export const GET = apiRoute({ permission: 'knowledge.read' }, async ({ searchParams }) => {
  const query = searchParams.get('q')?.trim()
  if (query) return { mode: 'search', results: await search(query) }

  const focus = searchParams.get('focus')?.trim()
  if (focus) {
    const depth = Math.min(3, Math.max(1, Number(searchParams.get('depth')) || 1))
    const result = await getNeighbourhood(focus, depth)
    return { mode: 'neighbourhood', ...result }
  }

  const graph = await loadKnowledgeGraph()
  return {
    mode: 'graph',
    nodeCount: graph.nodes.length,
    edgeCount: graph.edges.length,
    nodes: graph.nodes.filter((node) => node.kind === 'concept' || node.kind === 'region'),
    edges: graph.edges.filter((edge) => edge.from.startsWith('C-') || edge.from.startsWith('R-')),
  }
})
