// Browsing categories for the Knowledge Base — a coarser, more useful axis
// than the ontology's own `layer` (infrastructure/governance/cognition),
// which lumps very different things (an LXC and a DNS record and a storage
// volume) into one "infrastructure" bucket. Built from the ontology's
// `domain` field instead, which already draws these lines; this just
// groups the 9 domains into 6 browsing-sized buckets.
import type { EntityFilters } from './api'

export type Category = 'network' | 'fleet' | 'services' | 'storage' | 'identity' | 'knowledge'

export const categories: { id: Category; label: string }[] = [
  { id: 'fleet', label: 'Fleet' },
  { id: 'network', label: 'Network' },
  { id: 'services', label: 'Services' },
  { id: 'storage', label: 'Storage' },
  { id: 'identity', label: 'Identity' },
  { id: 'knowledge', label: 'Knowledge' }
]

// entity_types.domain -> Category. `external` folds into Network (isp-link,
// domain-registration are network-adjacent); `physical` folds into Fleet
// (ups/sensor/site support compute, browsing them separately fragments
// "what's running where"). `meta` (the abstract root "entity" type) and
// `cognition` (see KNOWLEDGE_TYPES below) are handled outside this map.
const DOMAIN_TO_CATEGORY: Record<string, Category> = {
  network: 'network',
  external: 'network',
  compute: 'fleet',
  physical: 'fleet',
  software: 'services',
  storage: 'storage',
  identity: 'identity'
}

// `cognition` is not one thing: document/investigation/runbook are genuine
// long-form knowledge, but the domain also holds execution/check/task/
// signal/approval/pattern/skill/classification/feedback — operational
// telemetry with its own pages (Operations, Signals, Learning). Mapping the
// whole domain to Knowledge pulled in 245 execution + 25 check entities that
// fan out to a handful of compute nodes via `targets`/`checks` edges,
// flooding the graph. Only the true knowledge types get a category; the
// rest are excluded from Knowledge Base browsing entirely (returns
// undefined, same treatment as the abstract `entity` root type).
const KNOWLEDGE_TYPES = new Set(['document', 'investigation', 'runbook'])

export function typeToCategory(type: string, domain: string): Category | undefined {
  if (KNOWLEDGE_TYPES.has(type)) return 'knowledge'
  if (domain === 'cognition') return undefined
  return DOMAIN_TO_CATEGORY[domain]
}

// Filter sets to fetch and merge for a category's table view. Most
// categories are one or two `domain` values; Knowledge is a handful of
// specific `type`s carved out of the (otherwise excluded) cognition domain.
export function filtersForCategory(category: Category): EntityFilters[] {
  if (category === 'knowledge') {
    return Array.from(KNOWLEDGE_TYPES).map((type) => ({ type }))
  }
  return Object.entries(DOMAIN_TO_CATEGORY)
    .filter(([, c]) => c === category)
    .map(([domain]) => ({ domain }))
}
