/**
 * studiograph about command
 *
 * Display or interactively edit the workspace ABOUT.md description.
 *
 * Usage:
 *   studiograph about              # display ABOUT.md
 *   studiograph about --edit       # open in $EDITOR
 *   studiograph about --interactive # step through each section
 *   studiograph about --set <file> # set from a file
 */
import { Command } from 'commander';
import { existsSync, readFileSync } from 'fs';
import { join } from 'path';
import { spawnSync } from 'child_process';
import { text, log, outro, isCancel } from '@clack/prompts';
import { Workspace } from '../../core/workspace.js';
const SECTIONS = ['Vision', 'Mission', 'Profile', 'Capabilities', 'Values'];
const TEMPLATE = SECTIONS.map(s => `## ${s}\n`).join('\n');
export function parseEditorCommand(editor) {
    const args = [];
    let current = '';
    let quote = null;
    let escaping = false;
    for (const ch of editor.trim()) {
        if (escaping) {
            current += ch;
            escaping = false;
            continue;
        }
        if (ch === '\\') {
            escaping = true;
            continue;
        }
        if (quote) {
            if (ch === quote)
                quote = null;
            else
                current += ch;
            continue;
        }
        if (ch === '"' || ch === "'") {
            quote = ch;
            continue;
        }
        if (/\s/.test(ch)) {
            if (current) {
                args.push(current);
                current = '';
            }
            continue;
        }
        current += ch;
    }
    if (escaping)
        current += '\\';
    if (quote)
        throw new Error('Unclosed quote in editor command');
    if (current)
        args.push(current);
    return args;
}
export const aboutCommand = new Command('about')
    .description('Display or edit workspace ABOUT.md')
    .option('-e, --edit', 'Open ABOUT.md in $EDITOR')
    .option('-i, --interactive', 'Step through each section interactively')
    .option('-s, --set <file>', 'Set ABOUT.md from a file')
    .action(async (opts) => {
    const workspace = new Workspace();
    if (!workspace.isWorkspace()) {
        console.error('Not a Studiograph workspace. Run `studiograph init` first.');
        process.exit(1);
    }
    const aboutPath = join(workspace.getWorkspacePath(), '.studiograph', 'ABOUT.md');
    if (opts.set) {
        if (!existsSync(opts.set)) {
            console.error(`File not found: ${opts.set}`);
            process.exit(1);
        }
        const content = readFileSync(opts.set, 'utf-8');
        workspace.writeAbout(content);
        console.log('ABOUT.md updated.');
        return;
    }
    if (opts.interactive) {
        // Parse existing content to pre-fill sections
        const existing = workspace.loadAbout() ?? '';
        const sectionContent = {};
        for (const section of SECTIONS) {
            const regex = new RegExp(`## ${section}\\s*\\n([\\s\\S]*?)(?=\\n## |$)`);
            const match = existing.match(regex);
            sectionContent[section] = match?.[1]?.trim() ?? '';
        }
        log.info('Describe your workspace — press Enter to skip a section.');
        for (const section of SECTIONS) {
            const value = await text({
                message: section,
                placeholder: sectionContent[section] || `Describe your ${section.toLowerCase()}...`,
                initialValue: sectionContent[section],
            });
            if (isCancel(value)) {
                outro('Cancelled');
                process.exit(0);
            }
            sectionContent[section] = value.trim();
        }
        const lines = [];
        for (const section of SECTIONS) {
            lines.push(`## ${section}\n`);
            if (sectionContent[section]) {
                lines.push(`${sectionContent[section]}\n`);
            }
        }
        workspace.writeAbout(lines.join('\n'));
        outro('ABOUT.md updated.');
        return;
    }
    if (opts.edit) {
        if (!existsSync(aboutPath)) {
            workspace.writeAbout(TEMPLATE);
        }
        const editor = process.env.EDITOR || process.env.VISUAL || 'vi';
        try {
            const [cmd, ...editorArgs] = parseEditorCommand(editor);
            if (!cmd)
                throw new Error('Editor command is empty');
            const result = spawnSync(cmd, [...editorArgs, aboutPath], { stdio: 'inherit', shell: false });
            if (result.error)
                throw result.error;
            if (result.status !== 0)
                throw new Error(`Editor exited with status ${result.status ?? 'unknown'}`);
        }
        catch (err) {
            console.error(`Failed to open editor: ${editor}`);
            if (err?.message)
                console.error(err.message);
            process.exit(1);
        }
        return;
    }
    // Default: display
    const content = workspace.loadAbout();
    if (!content) {
        console.log('No ABOUT.md found. Run `studiograph about --edit` to create one.');
        return;
    }
    console.log(content);
});
//# sourceMappingURL=about.js.map