#!/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 });
}

/**
 * Recursively remove all "required" arrays from a schema object.
 * This makes all properties optional for user input.
 */
function removeRequiredRecursively(obj) {
    if (obj === null || typeof obj !== 'object') {
        return obj;
    }

    if (Array.isArray(obj)) {
        return obj.map(removeRequiredRecursively);
    }

    const result = {};
    for (const [key, value] of Object.entries(obj)) {
        // Skip "required" arrays
        if (key === 'required' && Array.isArray(value)) {
            continue;
        }
        result[key] = removeRequiredRecursively(value);
    }
    return result;
}

try {
    // Generate schema using typescript-json-schema from CliConfig
    // Use --required to get full schema structure, then post-process to remove required arrays
    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'));
    
    // Remove all "required" arrays recursively to make all properties optional
    const schemaWithoutRequired = removeRequiredRecursively(schema);
    
    // 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. All properties are optional - the CLI provides sensible defaults.",
        "additionalProperties": schemaWithoutRequired.additionalProperties,
        "properties": schemaWithoutRequired.properties,
        "definitions": schemaWithoutRequired.definitions,
        "type": schemaWithoutRequired.type || "object"
    };
    
    // Remove undefined keys
    Object.keys(enhancedSchema).forEach(key => {
        if (enhancedSchema[key] === undefined) {
            delete enhancedSchema[key];
        }
    });
    
    // 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);
}
