import { readFileSync } from 'fs';
import { transformTemplate } from './transform/transformTemplate';
import { finalizeOutputOrThrow } from './finalize/finalizeOutput';
import { validateIr } from './validate/invariants';
import { parseZenFile } from './parseZenFile';
/**
 * Compile a .zen file into IR and CompiledTemplate
 */
export async function compileZen(filePath) {
    const source = readFileSync(filePath, 'utf-8');
    return compileZenSource(source, filePath);
}
/**
 * Compile Zen source string into IR and CompiledTemplate
 */
export async function compileZenSource(source, filePath, options) {
    // Parse with native bridge
    let ir = parseZenFile(filePath, source);
    // Resolve components if components directory is provided
    if (options?.componentsDir) {
        const { discoverComponents } = require('./discovery/componentDiscovery');
        const { resolveComponentsInIR } = require('./transform/componentResolver');
        // Component resolution may throw InvariantError — let it propagate
        const components = discoverComponents(options.componentsDir);
        ir = resolveComponentsInIR(ir, components);
    }
    // Validate all compiler invariants after resolution
    // Throws InvariantError if any invariant is violated
    validateIr(ir);
    const compiled = transformTemplate(ir);
    try {
        const finalized = await finalizeOutputOrThrow(ir, compiled);
        return { ir, compiled, finalized };
    }
    catch (error) {
        throw new Error(`Failed to finalize output for ${filePath}:\n${error.message}`);
    }
}
export { parseZenFile };
// Feature exports
export { discoverLayouts } from './discovery/layouts';
export { processLayout } from './transform/layoutProcessor';
export { bundlePageScript } from './bundler';
export { buildSSG } from './ssg-build';
export { buildSPA } from './spa-build';
export { generateBundleJS } from './runtime/bundle-generator';
export { generateRouteDefinition } from '@zenithbuild/router/manifest';
export { compileCss, compileCssAsync, resolveGlobalsCss } from './css';
export { loadZenithConfig } from './core/config/loader';
export { PluginRegistry, createPluginContext, getPluginDataByNamespace } from './core/plugins/registry';
export { createBridgeAPI, runPluginHooks, collectHookReturns, buildRuntimeEnvelope, clearHooks } from './core/plugins/bridge';
