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

export function scaffoldResource(model: OrganizationModel, spec: ResourceScaffoldSpec): OmScaffoldPlan {
  assertSystemExists(model, spec.systemPath)
  if (model.resources?.[spec.id] !== undefined) {
    throw new Error(`resource already exists: ${spec.id}`)
  }

  const label = spec.label ?? titleize(spec.id)
  const kind = spec.kind ?? 'workflow'
  const slug = slugify(spec.id)
  // Non-System scaffolds only create linked projects when explicitly requested.
  const writes = spec.withStubWorkflow
    ? [
        {
          path: `packages/elevasis-core/src/workflows/${slug}.stub.ts`,
          mode: 'create' as const,
          description: 'Optional workflow implementation stub. Runtime wiring remains manual.',
          content: `// Stub only. Replace with a real workflow implementation before registering the resource.\nexport const ${slug.replaceAll('-', '_')}Workflow = {\n  id: ${JSON.stringify(spec.id)}\n}\n`
        }
      ]
    : []

  return {
    intent: 'resource',
    id: spec.id,
    summary: `Scaffold ${kind} Resource "${spec.id}" for System "${spec.systemPath}".`,
    writes,
    edits: [
      {
        path: 'packages/elevasis-core/src/organization-model/resources.ts',
        description: 'Add this descriptor to platformResources/platformResourceDescriptors.',
        snippet: `${JSON.stringify(spec.id)}: {
  id: ${JSON.stringify(spec.id)},
  order: 0,
  kind: ${JSON.stringify(kind)},
  systemPath: ${JSON.stringify(spec.systemPath)},
  title: ${JSON.stringify(label)},
  ${spec.description === undefined ? '' : `description: ${JSON.stringify(spec.description)},\n  `}${spec.ownerRoleId === undefined ? '' : `ownerRoleId: ${JSON.stringify(spec.ownerRoleId)},\n  `}status: 'active',
  codeRefs: []
}`
      },
      {
        path: 'packages/elevasis-core/src/organization-model/topology.ts',
        description: 'Add topology relationships only when this resource triggers, uses, or requires approval from another OM node.',
        snippet: `// topologyRelationship({ from: topologyRef('resource', ${JSON.stringify(spec.id)}), kind: 'uses', to: ... })`
      }
    ],
    warnings: ['Resource ontology bindings are intentionally omitted until action/read/write contracts are known.'],
    nextSteps: [
      'Bind resource.ontology.actions/reads/writes after the ontology records exist.',
      `Run pnpm exec elevasis om:verify --scope ${spec.systemPath}.`
    ],
    projectCommand: spec.withProject
      ? `pnpm exec elevasis project:create --link-om ${spec.systemPath} --title "Add ${label} resource" --kind om-change`
      : undefined
  }
}
