/**
 * skill-author/scaffold.mjs — C4 scaffold generator.
 *
 * Given a skill name + description and the framework root, writes:
 *   - packages/framework/skills/apt-{name}/SKILL.md
 *   - packages/framework/src/__tests__/apt-{name}-skill-structure.test.ts
 *
 * Aborts (throws) if either target already exists — this is a one-shot tool
 * and v1 has no overwrite mode. Use --dry-run to preview the write targets
 * without touching disk.
 *
 * Pure Node; no apt-tools I/O conventions (no output() / no fail()) so the
 * helper can be unit-tested in isolation.
 */

import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { SKILL_NAME_REGEX } from './contract.mjs'
import { renderSkillStub } from './skill-template.mjs'
import { renderStructuralTest } from './test-template.mjs'

// The CLI passes a slug WITHOUT the `apt:` prefix. The SKILL_NAME_REGEX
// checks the full `apt:<slug>` form — we reuse it by prepending `apt:`.
const SLUG_REGEX = /^[a-z][a-z0-9-]*$/

/**
 * @param {{
 *   name: string,
 *   description: string,
 *   frameworkRoot: string,
 *   dryRun?: boolean,
 * }} opts
 * @returns {{ skillPath: string, testPath: string, files: string[], dryRun: boolean }}
 */
export function scaffoldSkill({ name, description, frameworkRoot, dryRun = false }) {
	if (typeof name !== 'string' || name.length === 0) {
		throw new Error('scaffoldSkill: name is required')
	}
	if (!SLUG_REGEX.test(name)) {
		throw new Error(
			`scaffoldSkill: name "${name}" is not a valid slug — must match ${SLUG_REGEX} (and resolve to ${SKILL_NAME_REGEX} after the apt: prefix)`,
		)
	}
	if (typeof description !== 'string' || description.length === 0) {
		throw new Error('scaffoldSkill: description is required')
	}
	if (typeof frameworkRoot !== 'string' || frameworkRoot.length === 0) {
		throw new Error('scaffoldSkill: frameworkRoot is required')
	}

	const skillDir = join(frameworkRoot, 'skills', `apt-${name}`)
	const skillPath = join(skillDir, 'SKILL.md')
	const testPath = join(frameworkRoot, 'src', '__tests__', `apt-${name}-skill-structure.test.ts`)

	if (existsSync(skillDir)) {
		throw new Error(`scaffoldSkill: skill directory already exists: ${skillDir}`)
	}
	if (existsSync(testPath)) {
		throw new Error(`scaffoldSkill: structural test file already exists: ${testPath}`)
	}

	const skillContent = renderSkillStub({ name, description })
	const testContent = renderStructuralTest({ name })

	if (!dryRun) {
		mkdirSync(skillDir, { recursive: true })
		writeFileSync(skillPath, skillContent, 'utf-8')
		// src/__tests__ must already exist (it's the canonical test dir) but be
		// defensive for unusual framework roots used by tests.
		mkdirSync(join(frameworkRoot, 'src', '__tests__'), { recursive: true })
		writeFileSync(testPath, testContent, 'utf-8')
	}

	return {
		skillPath,
		testPath,
		files: [skillPath, testPath],
		dryRun,
	}
}
