/**
 * Sidebar builder for Docusaurus
 * Automatically generates sidebar.js from .specweave/docs/ folder structure
 */
import * as path from 'path';
import * as fs from '../../utils/fs-native.js';
/**
 * Priority order for top-level folders
 * Lower number = appears first in sidebar
 */
const FOLDER_PRIORITY = {
    strategy: 1,
    specs: 2,
    architecture: 3,
    delivery: 4,
    operations: 5,
    governance: 6,
    projects: 7 // Multi-project support
};
/**
 * Default folders to exclude from sidebar
 */
const DEFAULT_EXCLUDE_FOLDERS = [
    'node_modules',
    '.git',
    '.DS_Store',
    'legacy' // Brownfield imports (temporary, not for display)
];
/**
 * Build sidebar from folder structure
 */
export async function buildSidebar(options) {
    const { docsPath, excludeFolders = DEFAULT_EXCLUDE_FOLDERS, maxDepth = 5 } = options;
    // Check if docs path exists
    if (!await fs.pathExists(docsPath)) {
        throw new Error(`Documentation path does not exist: ${docsPath}`);
    }
    // Scan folders and build sidebar items
    const items = await scanFolder(docsPath, docsPath, excludeFolders, 0, maxDepth);
    // Sort by priority (strategy first, governance last)
    const sortedItems = sortByPriority(items);
    return {
        docs: sortedItems
    };
}
/**
 * Scan folder recursively and build sidebar items
 */
async function scanFolder(basePath, currentPath, excludeFolders, depth, maxDepth) {
    if (depth >= maxDepth) {
        return [];
    }
    const items = [];
    try {
        const entries = await fs.readdir(currentPath, { withFileTypes: true });
        // Separate folders and files
        const folders = entries.filter(e => e.isDirectory() && !excludeFolders.includes(e.name));
        const files = entries.filter(e => e.isFile() && e.name.endsWith('.md'));
        // Process folders first (categories)
        for (const folder of folders) {
            const folderPath = path.join(currentPath, folder.name);
            const childItems = await scanFolder(basePath, folderPath, excludeFolders, depth + 1, maxDepth);
            if (childItems.length > 0) {
                items.push({
                    type: 'category',
                    label: formatLabel(folder.name),
                    items: childItems
                });
            }
        }
        // Process markdown files (docs)
        for (const file of files) {
            const relativePath = path.relative(basePath, path.join(currentPath, file.name));
            const docId = relativePath.replace(/\.md$/, '').replace(/\\/g, '/');
            items.push({
                type: 'doc',
                id: docId
            });
        }
        return items;
    }
    catch (error) {
        console.error(`Error scanning folder ${currentPath}:`, error);
        return [];
    }
}
/**
 * Sort sidebar items by priority
 */
function sortByPriority(items) {
    return items.sort((a, b) => {
        // Extract folder name from label
        const aFolder = a.label?.toLowerCase().replace(/\s+/g, '-') || '';
        const bFolder = b.label?.toLowerCase().replace(/\s+/g, '-') || '';
        // Get priorities (default to 999 if not found)
        const aPriority = FOLDER_PRIORITY[aFolder] || 999;
        const bPriority = FOLDER_PRIORITY[bFolder] || 999;
        // Sort by priority
        if (aPriority !== bPriority) {
            return aPriority - bPriority;
        }
        // If same priority, sort alphabetically
        return aFolder.localeCompare(bFolder);
    });
}
/**
 * Format folder name to human-readable label
 * Examples:
 * - "strategy" → "Strategy"
 * - "architecture" → "Architecture"
 * - "adr" → "ADRs"
 * - "my-feature-spec" → "My Feature Spec"
 */
function formatLabel(folderName) {
    // Special cases
    const specialCases = {
        adr: 'ADRs',
        adrs: 'ADRs',
        hld: 'HLD',
        lld: 'LLD',
        prd: 'PRDs',
        okr: 'OKRs',
        api: 'API',
        cli: 'CLI',
        ui: 'UI',
        ux: 'UX',
        sre: 'SRE',
        devops: 'DevOps',
        mlops: 'MLOps',
        k8s: 'Kubernetes'
    };
    const normalized = folderName.toLowerCase();
    if (specialCases[normalized]) {
        return specialCases[normalized];
    }
    // Convert kebab-case or snake_case to Title Case
    return folderName
        .replace(/[-_]/g, ' ')
        .split(' ')
        .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
        .join(' ');
}
/**
 * Generate sidebars.js content as string
 */
export function generateSidebarsJS(sidebar) {
    return `/**
 * Auto-generated sidebar for SpecWeave documentation
 * Generated: ${new Date().toISOString()}
 *
 * DO NOT EDIT THIS FILE MANUALLY
 * Regenerate with: sw:docs preview
 */

module.exports = ${JSON.stringify(sidebar, null, 2)};
`;
}
/**
 * Write sidebar to file
 */
export async function writeSidebar(filePath, sidebar) {
    const content = generateSidebarsJS(sidebar);
    await fs.ensureDir(path.dirname(filePath));
    await fs.writeFile(filePath, content, 'utf-8');
}
/**
 * Count total documents in sidebar
 */
export function countDocuments(sidebar) {
    let count = 0;
    function traverse(items) {
        for (const item of items) {
            if (item.type === 'doc') {
                count++;
            }
            else if (item.type === 'category' && item.items) {
                traverse(item.items);
            }
        }
    }
    traverse(sidebar.docs);
    return count;
}
/**
 * Count total categories in sidebar
 */
export function countCategories(sidebar) {
    let count = 0;
    function traverse(items) {
        for (const item of items) {
            if (item.type === 'category') {
                count++;
                if (item.items) {
                    traverse(item.items);
                }
            }
        }
    }
    traverse(sidebar.docs);
    return count;
}
//# sourceMappingURL=sidebar-builder.js.map