import type { OrganizationModel } from '..'
import { assertSystemExists, slugify, titleize } from './helpers'
import type { KnowledgeNodeScaffoldSpec, OmScaffoldPlan } from './types'

export function scaffoldKnowledgeNode(model: OrganizationModel, spec: KnowledgeNodeScaffoldSpec): OmScaffoldPlan {
  if (spec.systemPath !== undefined) assertSystemExists(model, spec.systemPath)
  if (model.knowledge?.[spec.id] !== undefined) {
    throw new Error(`knowledge node already exists: ${spec.id}`)
  }

  const title = spec.label ?? titleize(spec.id.replace(/^knowledge\./, ''))
  const slug = slugify(spec.id.replace(/^knowledge\./, ''))
  const kind = spec.kind ?? 'reference'
  const links = spec.systemPath === undefined ? '' : `links:\n  - system:${spec.systemPath}\n`
  const ownerIds = spec.ownerRoleId === undefined ? '' : `ownerIds:\n  - ${spec.ownerRoleId}\n`
  // Non-System scaffolds only create linked projects when explicitly requested.

  return {
    intent: 'knowledge',
    id: spec.id,
    summary: `Scaffold ${kind} knowledge node "${spec.id}".`,
    writes: [
      {
        path: `packages/elevasis-core/src/knowledge/nodes/${slug}.mdx.stub`,
        mode: 'create',
        description: 'Knowledge node MDX skeleton.',
        content: `---\nid: ${spec.id}\nkind: ${kind}\ntitle: ${JSON.stringify(title)}\nsummary: ${JSON.stringify(spec.description ?? `${title} knowledge node.`)}\n${links}${ownerIds}updatedAt: 2026-05-15\n---\n\n## Overview\n\nCapture the durable operating knowledge here.\n`
      }
    ],
    edits: [
      {
        path: 'packages/elevasis-core/src/organization-model/knowledge.ts',
        description: 'Register this generated node after replacing the .stub suffix.',
        snippet: `${JSON.stringify(spec.id)}`
      }
    ],
    warnings: [],
    nextSteps: [
      'Replace the .stub suffix after the node is ready to become canonical.',
      spec.systemPath === undefined
        ? 'Add links to the OM nodes this knowledge governs.'
        : `Run pnpm exec elevasis om:verify --scope ${spec.systemPath}.`
    ],
    projectCommand:
      spec.withProject && spec.systemPath !== undefined
        ? `pnpm exec elevasis project:create --link-om ${spec.systemPath} --title "Add ${title} knowledge" --kind om-change`
        : undefined
  }
}
