/**
 * Admin adapter — authoring.
 *
 * Programmatic specialist / skill file creation. Authoritative home for
 * the markdown builders that used to live in
 * `src/dashboard/routes/authoring.ts` (POST handlers are being retired
 * in PR7 Phase 3). Reachable from CLI and hosts without going through MCP.
 */
import * as fs from 'node:fs';
import * as path from 'node:path';
/** Sanitize an id to safe filesystem characters. */
function safeId(raw) {
    return raw.replace(/[^a-z0-9._-]/gi, '-').toLowerCase().slice(0, 120);
}
/**
 * Render a specialist definition to markdown in the format expected by
 * the specialist detail loader at `.agents/specialists/<id>.md`.
 */
function specialistToMarkdown(input) {
    const name = input.name;
    const division = input.division ?? 'custom';
    const description = input.description ?? '';
    const emoji = input.emoji ?? '🤖';
    const authority = input.authority ?? 'advisory';
    const domains = input.domains ?? [];
    const mission = input.mission ?? '';
    const rules = input.rules ?? [];
    const workflow = input.workflow ?? [];
    const deliverables = input.deliverables ?? [];
    const lines = [
        `# ${emoji} ${name}`,
        '',
        `**Division**: ${division}  `,
        `**Authority**: ${authority}  `,
        `**Domains**: ${domains.join(', ') || '—'}  `,
        '',
        '## Description',
        '',
        description || '_No description provided._',
        '',
        '## Mission',
        '',
        mission || '_No mission provided._',
        '',
    ];
    if (rules.length) {
        lines.push('## Rules', '');
        rules.forEach((r) => lines.push(`- ${r}`));
        lines.push('');
    }
    if (workflow.length) {
        lines.push('## Workflow', '');
        workflow.forEach((w) => lines.push(`- ${w}`));
        lines.push('');
    }
    if (deliverables.length) {
        lines.push('## Deliverables', '');
        deliverables.forEach((d) => lines.push(`- ${d}`));
        lines.push('');
    }
    return lines.join('\n');
}
/**
 * Render a skill definition to markdown for `.agents/skills/<id>.md`.
 */
function skillToMarkdown(input) {
    const name = input.name;
    const description = input.description ?? '';
    const trigger = input.trigger ?? '';
    const steps = input.steps ?? [];
    const lines = [
        `# ${name}`,
        '',
        description || '_No description provided._',
        '',
    ];
    if (trigger) {
        lines.push('## Trigger', '', trigger, '');
    }
    if (steps.length) {
        lines.push('## Steps', '');
        steps.forEach((s) => lines.push(`- ${s}`));
        lines.push('');
    }
    return lines.join('\n');
}
function requireName(name, kind) {
    if (typeof name !== 'string' || name.trim().length === 0) {
        throw new Error(`admin.createAuthoring: ${kind} name is required`);
    }
    return name.trim();
}
export function createAuthoringAdmin(repoRoot) {
    return {
        async createSpecialist(input) {
            const name = requireName(input.name, 'specialist');
            const specialistId = safeId(name);
            const dir = path.join(repoRoot, '.agents', 'specialists');
            const filePath = path.join(dir, `${specialistId}.md`);
            const content = specialistToMarkdown({ ...input, name });
            await fs.promises.mkdir(dir, { recursive: true });
            await fs.promises.writeFile(filePath, content, 'utf8');
            return { ok: true, specialistId, filePath };
        },
        async createSkill(input) {
            const name = requireName(input.name, 'skill');
            const skillId = safeId(name);
            const dir = path.join(repoRoot, '.agents', 'skills');
            const filePath = path.join(dir, `${skillId}.md`);
            const content = skillToMarkdown({ ...input, name });
            await fs.promises.mkdir(dir, { recursive: true });
            await fs.promises.writeFile(filePath, content, 'utf8');
            return { ok: true, skillId, filePath };
        },
    };
}
