#!/usr/bin/env node

const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');

console.log('Generating JSON schema from CliConfig interface...');

const schemaDir = path.join(__dirname, '..', 'dist', 'schemas');
const schemaFile = path.join(schemaDir, 'iocd.cli.config.schema.json');

// Ensure the schemas directory exists
if (!fs.existsSync(schemaDir)) {
    fs.mkdirSync(schemaDir, { recursive: true });
}

try {
    // Generate schema using typescript-json-schema
    // Point directly to the source file to avoid compilation issues
    execSync(
        `npx typescript-json-schema ./src/services/config/cli.config.ts CliConfig --required --noExtraProps --out ${schemaFile}`,
        { 
            cwd: path.join(__dirname, '..'),
            stdio: 'inherit' 
        }
    );

    // Read the generated schema
    const schema = JSON.parse(fs.readFileSync(schemaFile, 'utf8'));
    
    // Add metadata at the beginning, preserving proper order
    const enhancedSchema = {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "$id": "https://unpkg.com/@interopio/iocd-cli/schemas/iocd.cli.config.schema.json",
        "title": "io.Connect Desktop CLI Configuration",
        "description": "Configuration schema for io.Connect Desktop CLI projects",
        "additionalProperties": schema.additionalProperties,
        "properties": schema.properties,
        "required": schema.required,
        "type": schema.type || "object"
    };
    
    // Write back the updated schema
    fs.writeFileSync(schemaFile, JSON.stringify(enhancedSchema, null, 2));
    
    console.log('✅ JSON schema generated successfully at:', schemaFile);
} catch (error) {
    console.error('❌ Error generating JSON schema:', error.message);
    process.exit(1);
}
