/**
 * AI-Optimized Spec Loader Utility
 *
 * Loads SpecVerse YAML files and generates AIOptimizedSpec using:
 * 1. UnifiedSpecVerseParser - Handles YAML parsing, imports, conventions
 * 2. AIViewGenerator - Generates optimized spec with inference
 *
 * This utility eliminates duplicate parsing logic across all generators.
 */
import { readFileSync, existsSync } from 'fs';
import { resolve, dirname } from 'path';
import { fileURLToPath } from 'url';
import { createRequire } from 'module';
import { UnifiedSpecVerseParser } from '../../parser/index.js';
import { AIViewGenerator } from '../../generators/index.js';
// ES module equivalent of __dirname
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const require = createRequire(import.meta.url);
// Load JSON schema from engine-entities (single source of truth)
const getSchemaPath = () => {
    // Try engine-entities package first (single source of truth)
    try {
        const entitiesPkg = dirname(require.resolve('@specverse/entities/package.json'));
        const entitiesSchema = resolve(entitiesPkg, 'schema', 'SPECVERSE-SCHEMA.json');
        if (existsSync(entitiesSchema))
            return entitiesSchema;
    }
    catch { /* engine-entities not available */ }
    // Fallback paths
    const possiblePaths = [
        resolve(process.cwd(), 'schema/SPECVERSE-SCHEMA.json'),
        resolve(__dirname, '../../../schema/SPECVERSE-SCHEMA.json'),
        resolve(__dirname, '../../schema/SPECVERSE-SCHEMA.json'),
    ];
    for (const path of possiblePaths) {
        if (existsSync(path))
            return path;
    }
    return possiblePaths[0];
};
const schemaPath = getSchemaPath();
const schemaJson = JSON.parse(readFileSync(schemaPath, 'utf8'));
/**
 * Load and generate AIOptimizedSpec from a SpecVerse YAML file
 */
export function loadAIOptimizedSpec(yamlFile, options = {}) {
    try {
        // 1. Read YAML file
        const yamlContent = readFileSync(yamlFile, 'utf8');
        // 2. Parse with UnifiedSpecVerseParser (handles imports, conventions, validation)
        const parser = new UnifiedSpecVerseParser(schemaJson);
        const result = parser.parse(yamlContent, 'specly');
        // Check for parse errors
        if (result.errors && result.errors.length > 0) {
            const errorMessages = result.errors
                .map((err) => `  - ${err.message} (line ${err.line || '?'}, col ${err.column || '?'})`)
                .join('\n');
            throw new Error(`Parse errors in ${yamlFile}:\n${errorMessages}`);
        }
        // Check for warnings (non-fatal)
        if (result.warnings && result.warnings.length > 0) {
            console.warn(`⚠️  Warnings in ${yamlFile}:`);
            result.warnings.forEach((warn) => {
                console.warn(`  - ${warn.message}`);
            });
        }
        // 3. Generate AIOptimizedSpec (runs inference, expands CURED, etc.)
        const generator = new AIViewGenerator();
        const optimized = generator.generate(result.ast, options);
        return optimized;
    }
    catch (error) {
        // Provide helpful error messages
        if (error.code === 'ENOENT') {
            throw new Error(`File not found: ${yamlFile}`);
        }
        throw error;
    }
}
/**
 * Load AIOptimizedSpec with deployment filtering
 */
export function loadForDeployment(yamlFile, deploymentName, instanceName) {
    return loadAIOptimizedSpec(yamlFile, {
        deployment: deploymentName,
        instance: instanceName
    });
}
/**
 * Load AIOptimizedSpec with manifest configuration
 */
export function loadWithManifest(yamlFile, manifestConfig) {
    return loadAIOptimizedSpec(yamlFile, {
        manifest: manifestConfig
    });
}
/**
 * Get component metadata from AIOptimizedSpec
 */
export function getComponentMetadata(spec) {
    return {
        name: spec.metadata.component,
        version: spec.metadata.version,
        description: spec.metadata.description,
        tags: spec.metadata.tags,
        deployment: spec.metadata.deployment,
        instance: spec.metadata.instance,
        manifest: spec.metadata.manifest
    };
}
/**
 * Get all models from AIOptimizedSpec
 */
export function getModels(spec) {
    return spec.models || [];
}
/**
 * Get all controllers from AIOptimizedSpec
 */
export function getControllers(spec) {
    return spec.controllers || [];
}
/**
 * Get all services from AIOptimizedSpec
 */
export function getServices(spec) {
    return spec.services || [];
}
/**
 * Get all events from AIOptimizedSpec
 */
export function getEvents(spec) {
    return spec.events || [];
}
/**
 * Get infrastructure requirements from AIOptimizedSpec
 */
export function getInfrastructure(spec) {
    return spec.infrastructure || {};
}
//# sourceMappingURL=ai-spec-loader.js.map