"use strict";
/**
 * Markdown Documentation Generator
 * Generates markdown documentation from workflow definitions
 * Supports both intent-based (declarative) and literal (legacy) documentation
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.MarkdownDocumentationGenerator = void 0;
const version_discovery_1 = require("../utils/version-discovery");
const template_registry_1 = require("./templates/template-registry");
const path = __importStar(require("path"));
class MarkdownDocumentationGenerator {
    id = 'markdown-docs';
    name = 'Markdown Documentation Generator';
    description = 'Generates markdown documentation from workflows';
    format = 'markdown';
    async generate(context) {
        const { workflow, extendedWorkflow, outputDirectory } = context;
        const files = [];
        // Support both extendedWorkflow.documentation (new) and workflow.documentation (old)
        const documentation = extendedWorkflow?.documentation || workflow.documentation;
        if (!documentation) {
            return { files: [] };
        }
        // NEW: Intent-based documentation generation
        if (documentation.intents && documentation.intents.length > 0) {
            const intentFiles = await this.generateFromIntents(context);
            files.push(...intentFiles);
        }
        // LEGACY: Literal documentation (backward compatibility)
        if (!workflow.documentation) {
            return { files };
        }
        // Generate user documentation
        if (workflow.documentation.user_docs) {
            for (const doc of workflow.documentation.user_docs) {
                files.push({
                    path: path.join(outputDirectory, 'docs', 'user', `${this.slugify(doc.title)}.md`),
                    content: this.generateUserDoc(doc, workflow),
                    overwrite: true,
                });
            }
            // Generate index for user docs
            files.push({
                path: path.join(outputDirectory, 'docs', 'user', 'README.md'),
                content: this.generateUserDocsIndex(workflow.documentation.user_docs, workflow),
                overwrite: true,
            });
        }
        // Generate developer documentation
        if (workflow.documentation.developer_docs) {
            for (const doc of workflow.documentation.developer_docs) {
                files.push({
                    path: path.join(outputDirectory, 'docs', 'developer', `${this.slugify(doc.title)}.md`),
                    content: this.generateDeveloperDoc(doc, workflow),
                    overwrite: true,
                });
            }
            // Generate index for developer docs
            files.push({
                path: path.join(outputDirectory, 'docs', 'developer', 'README.md'),
                content: this.generateDeveloperDocsIndex(workflow.documentation.developer_docs, workflow),
                overwrite: true,
            });
        }
        // Generate main README
        files.push({
            path: path.join(outputDirectory, 'docs', 'README.md'),
            content: this.generateMainReadme(workflow),
            overwrite: true,
        });
        return { files };
    }
    generateUserDoc(doc, workflow) {
        let content = `# ${doc.title}\n\n`;
        content += `> Documentation for ${workflow.workflow.name}\n\n`;
        for (const section of doc.sections) {
            content += `## ${section.heading}\n\n`;
            content += `${section.content}\n\n`;
            if (section.steps && section.steps.length > 0) {
                content += `### Steps\n\n`;
                for (let i = 0; i < section.steps.length; i++) {
                    content += `${i + 1}. ${section.steps[i]}\n`;
                }
                content += '\n';
            }
            if (section.examples && section.examples.length > 0) {
                content += `### Examples\n\n`;
                for (const example of section.examples) {
                    content += `**${example.language}:**\n\n`;
                    content += '```' + example.language + '\n';
                    content += example.code + '\n';
                    content += '```\n\n';
                }
            }
        }
        content += `---\n\n`;
        content += `*Generated from workflow: ${workflow.workflow.id} v${workflow.workflow.version}*\n`;
        return content;
    }
    generateDeveloperDoc(doc, workflow) {
        let content = `# ${doc.title}\n\n`;
        content += `> Developer documentation for ${workflow.workflow.name}\n\n`;
        for (const section of doc.sections) {
            content += `## ${section.heading}\n\n`;
            content += `${section.content}\n\n`;
            if (section.examples && section.examples.length > 0) {
                content += `### Code Examples\n\n`;
                for (const example of section.examples) {
                    content += `#### ${example.language}\n\n`;
                    content += '```' + example.language + '\n';
                    content += example.code + '\n';
                    content += '```\n\n';
                }
            }
        }
        content += `---\n\n`;
        content += `*Generated from workflow: ${workflow.workflow.id} v${workflow.workflow.version}*\n`;
        return content;
    }
    generateUserDocsIndex(docs, workflow) {
        let content = `# User Documentation\n\n`;
        content += `Documentation for ${workflow.workflow.name}\n\n`;
        content += `## Available Guides\n\n`;
        for (const doc of docs) {
            content += `- [${doc.title}](./${this.slugify(doc.title)}.md)\n`;
        }
        content += '\n';
        return content;
    }
    generateDeveloperDocsIndex(docs, workflow) {
        let content = `# Developer Documentation\n\n`;
        content += `Technical documentation for ${workflow.workflow.name}\n\n`;
        content += `## Available Documentation\n\n`;
        for (const doc of docs) {
            content += `- [${doc.title}](./${this.slugify(doc.title)}.md)\n`;
        }
        content += '\n';
        return content;
    }
    generateMainReadme(workflow) {
        let content = `# ${workflow.workflow.name}\n\n`;
        content += `${workflow.workflow.description}\n\n`;
        content += `## Documentation\n\n`;
        if (workflow.documentation?.user_docs) {
            content += `- [User Documentation](./user/README.md)\n`;
        }
        if (workflow.documentation?.developer_docs) {
            content += `- [Developer Documentation](./developer/README.md)\n`;
        }
        content += '\n## Stack Components\n\n';
        for (const [name, component] of Object.entries(workflow.stack)) {
            const comp = component;
            content += `- **${name}**: ${comp.type} (${comp.technology})\n`;
        }
        content += '\n## Workflow Information\n\n';
        content += `- **ID**: ${workflow.workflow.id}\n`;
        content += `- **Version**: ${workflow.workflow.version}\n`;
        if (workflow.workflow.domains && workflow.workflow.domains.length > 0) {
            content += `- **Domains**: ${workflow.workflow.domains.join(', ')}\n`;
        }
        content += '\n## Regenerating Code\n\n';
        content += `This project was generated from a workflow definition file: \`${workflow.workflow.id}.workflow.yaml\`\n\n`;
        content += `To regenerate or update the code:\n\n`;
        content += '```bash\n';
        content += `# Install bangstack if not already installed\n`;
        content += `npm install -g bangstack\n\n`;
        content += `# Regenerate from the workflow file\n`;
        content += `bang generate ${workflow.workflow.id}.workflow.yaml --output .\n`;
        content += '```\n\n';
        content += `**Note**: The workflow file is included in the generated output for your reference and to enable regeneration.\n`;
        content += '\n---\n\n';
        content += `*This documentation was automatically generated from the workflow definition.*\n`;
        return content;
    }
    /**
     * Generate documentation from intents (NEW approach)
     */
    async generateFromIntents(context) {
        const { workflow, extendedWorkflow, outputDirectory } = context;
        const files = [];
        // Get documentation intents
        const documentation = extendedWorkflow?.documentation || workflow.documentation;
        if (!documentation?.intents) {
            return files;
        }
        // Discover versions from package.json files
        const versions = await (0, version_discovery_1.discoverVersions)(outputDirectory);
        // Process each intent
        for (const intent of documentation.intents) {
            // Find appropriate template for this intent
            const template = template_registry_1.templateRegistry.findTemplate(intent);
            if (!template) {
                console.warn(`No template found for intent type: ${intent.type}`);
                continue;
            }
            // Create template context
            const templateContext = {
                intent,
                workflow,
                extendedWorkflow,
                versions,
                outputDirectory,
            };
            // Generate content from template
            const content = template.generate(templateContext);
            // Get output path
            const filename = template.getOutputPath(intent);
            const filepath = path.join(outputDirectory, 'docs', filename);
            // Determine overwrite policy
            const overwrite = intent.overwrite !== 'never';
            files.push({
                path: filepath,
                content,
                overwrite,
            });
        }
        // Generate index file if multiple intents
        if (documentation.intents.length > 0) {
            files.push({
                path: path.join(outputDirectory, 'docs', 'README.md'),
                content: this.generateIntentBasedIndex(documentation.intents, workflow),
                overwrite: true,
            });
        }
        return files;
    }
    /**
     * Generate index file for intent-based documentation
     */
    generateIntentBasedIndex(intents, workflow) {
        let content = `# ${workflow.workflow.name} - Documentation\n\n`;
        content += `${workflow.workflow.description}\n\n`;
        // Group by audience
        const userIntents = intents.filter(i => i.audience === 'user' || i.audience === 'both');
        const devIntents = intents.filter(i => i.audience === 'developer' || i.audience === 'both');
        if (userIntents.length > 0) {
            content += `## User Guides\n\n`;
            for (const intent of userIntents) {
                const title = this.getIntentTitle(intent);
                const filename = this.getIntentFilename(intent);
                content += `- [${title}](./${filename})\n`;
            }
            content += '\n';
        }
        if (devIntents.length > 0) {
            content += `## Developer Documentation\n\n`;
            for (const intent of devIntents) {
                const title = this.getIntentTitle(intent);
                const filename = this.getIntentFilename(intent);
                content += `- [${title}](./${filename})\n`;
            }
            content += '\n';
        }
        content += `## Regenerating Documentation\n\n`;
        content += `This documentation was generated from the workflow file. To regenerate:\n\n`;
        content += '```bash\n';
        content += `bang generate ${workflow.workflow.id}.workflow.yaml --output .\n`;
        content += '```\n\n';
        return content;
    }
    /**
     * Get display title for intent
     */
    getIntentTitle(intent) {
        const typeNames = {
            tutorial: 'Tutorial',
            methodology: 'Methodology',
            troubleshooting: 'Troubleshooting',
            api_reference: 'API Reference',
            setup_guide: 'Setup Guide',
            best_practices: 'Best Practices',
            architecture: 'Architecture',
        };
        const typeName = typeNames[intent.type] || this.capitalize(intent.type);
        if (intent.scope) {
            return `${typeName}: ${this.capitalize(intent.scope)}`;
        }
        return typeName;
    }
    /**
     * Get filename for intent
     */
    getIntentFilename(intent) {
        if (intent.outputPath) {
            return intent.outputPath;
        }
        return intent.scope
            ? `${intent.type}-${this.slugify(intent.scope)}.md`
            : `${intent.type}.md`;
    }
    /**
     * Capitalize first letter
     */
    capitalize(text) {
        return text.charAt(0).toUpperCase() + text.slice(1);
    }
    slugify(text) {
        return text
            .toLowerCase()
            .replace(/[^\w\s-]/g, '')
            .replace(/\s+/g, '-')
            .replace(/-+/g, '-')
            .trim();
    }
}
exports.MarkdownDocumentationGenerator = MarkdownDocumentationGenerator;
//# sourceMappingURL=markdown-generator.js.map