#!/usr/bin/env nu
# Generate configuration files from Nickel schemas
#
# Usage: nu generate-configs.nu [--mode <dev|prod|test>] [--output <dir>]

def main [
    --mode: string = "dev"         # Configuration mode
    --output: string = ".kogral"   # Output directory
] {
    print $"(ansi green_bold)KOGRAL Config Generator(ansi reset)"
    print $"Mode: ($mode)"
    print $"Output: ($output)"

    # Phase 1: Validate mode
    let valid_modes = ["dev" "prod" "test"]
    if ($mode | str downcase) not-in $valid_modes {
        print $"(ansi red)Error: Invalid mode. Must be: (ansi reset)($valid_modes | str join ', ')"
        exit 1
    }

    # Phase 2: Export Nickel schema to JSON
    print ""
    print $"(ansi cyan_bold)Exporting Nickel configuration...(ansi reset)"

    let nickel_file = $".typedialog/kogral/modes/($mode).ncl"
    if not ($nickel_file | path exists) {
        print $"(ansi red)Error: Mode file not found: $nickel_file(ansi reset)"
        exit 1
    }

    # Phase 3: Run Nickel export
    let output_file = $"($output)/config.json"
    nickel export --format json $nickel_file | save --force $output_file
    print $"(ansi green)✓ Config exported to $output_file(ansi reset)"

    # Phase 4: Validate generated config
    print ""
    print $"(ansi cyan_bold)Validating configuration...(ansi reset)"

    let config_json = open $output_file
    print $"(ansi green)✓ Configuration is valid(ansi reset)"
    if ($config_json | type) == "record" {
        let section_count = ($config_json | length)
        print $"  - Sections: $section_count"
        if ($config_json | has "embeddings") {
            let embeddings_enabled = $config_json.embeddings.enabled
            print $"  - Embeddings: $embeddings_enabled"
        }
    }

    print ""
    print $"(ansi green_bold)✓ Configuration generation complete(ansi reset)"
}

main
