import { readFileSync, existsSync, readdirSync } from 'fs';
import { join } from 'path';
import { parseDocsConfig } from './schema';
/**
 * Configuration Loader
 * 
 * Utilities for loading and caching docs.json configuration
 * Uses synchronous fs operations for compatibility with Next.js Turbopack
 */ // Cache for loaded configuration
let configCache = null;
let configCachePath = null;
/**
 * Load docs.json configuration from a directory
 */ export function loadDocsConfig(docsDir) {
    const configFilePath = join(docsDir, 'docs.json');
    // Return cached config if path matches
    if (configCache && configCachePath === configFilePath) {
        return configCache;
    }
    try {
        if (!existsSync(configFilePath)) {
            throw new Error(`docs.json not found at ${configFilePath}`);
        }
        const configContent = readFileSync(configFilePath, 'utf-8');
        const rawConfig = JSON.parse(configContent);
        const config = parseDocsConfig(rawConfig);
        // Cache the result
        configCache = config;
        configCachePath = configFilePath;
        return config;
    } catch (error) {
        if (error instanceof Error) {
            throw new Error(`Failed to load docs.json: ${error.message}`);
        }
        throw error;
    }
}
/**
 * Load configuration without throwing (returns null on failure)
 */ export function safeLoadDocsConfig(docsDir) {
    try {
        return loadDocsConfig(docsDir);
    } catch  {
        return null;
    }
}
/**
 * Clear the configuration cache
 */ export function clearConfigCache() {
    configCache = null;
    configCachePath = null;
}
/**
 * Check if a docs.json file exists in a directory
 */ export function hasDocsConfig(docsDir) {
    return existsSync(join(docsDir, 'docs.json'));
}
/**
 * Get the content directory path from configuration
 */ export function getContentDir(docsDir) {
    return docsDir;
}
/**
 * Resolve a page path to a file path
 */ export function resolvePagePath(docsDir, pagePath) {
    const contentDir = getContentDir(docsDir);
    const extensions = [
        '.mdx',
        '.md'
    ];
    // Try different extensions
    for (const ext of extensions){
        const filePath = join(contentDir, `${pagePath}${ext}`);
        if (existsSync(filePath)) {
            return filePath;
        }
    }
    // Try as directory with index file
    for (const ext of extensions){
        const indexPath = join(contentDir, pagePath, `index${ext}`);
        if (existsSync(indexPath)) {
            return indexPath;
        }
    }
    return null;
}
/**
 * Load page content from a resolved path
 */ export function loadPageContent(filePath) {
    return readFileSync(filePath, 'utf-8');
}
/**
 * List all MDX files in a directory recursively
 */ export function listMdxFiles(dir) {
    const files = [];
    function walk(currentDir) {
        const entries = readdirSync(currentDir, {
            withFileTypes: true
        });
        for (const entry of entries){
            const fullPath = join(currentDir, entry.name);
            if (entry.isDirectory()) {
                if (!entry.name.startsWith('.') && entry.name !== 'node_modules') {
                    walk(fullPath);
                }
            } else if (entry.isFile() && (entry.name.endsWith('.mdx') || entry.name.endsWith('.md'))) {
                files.push(fullPath);
            }
        }
    }
    walk(dir);
    return files;
}
