#!/usr/bin/env nu

# Generate TOML configs from Nickel sources
# Exports Nickel configs to TOML format for use by Rust services
# Usage: nu generate-configs.nu orchestrator solo
# Usage: nu generate-configs.nu control-center multiuser

use ansi.nu
use external.nu
use paths.nu

export def main [
    service: string    # Service: orchestrator | control-center | mcp-server | vault-service | extension-registry | rag | ai-service | provisioning-daemon
    mode: string       # Mode: solo | multiuser | cicd | enterprise
]: nothing -> nothing {
    # Validate inputs
    paths validate-service $service
    paths validate-mode $mode

    let nickel_path: string = (paths get-config-path $service $mode)
    let toml_path: string = (paths get-output-config-path $service $mode)

    ansi print-working $"Generating TOML config for ($service) in ($mode) mode"
    print $"  From: ($nickel_path)"
    print $"  To:   ($toml_path)"

    # Validate Nickel file first
    paths assert-file-exists $nickel_path

    ansi print-validate "Checking Nickel syntax..."
    let validate_result: record<exit_code: int, stdout: string, stderr: string> = (external run-cmd "nickel" ["typecheck", $nickel_path])

    if $validate_result.exit_code != 0 {
        ansi print-error "Nickel validation failed"
        print $validate_result.stderr
        exit 1
    }

    ansi print-success "Nickel syntax valid"

    # Export to TOML
    ansi print-working "Exporting to TOML format..."
    let export_result: record<exit_code: int, stdout: string, stderr: string> = (external run-cmd "nickel" ["export", "--format", "toml", $nickel_path])

    if $export_result.exit_code != 0 {
        ansi print-error "Nickel export failed"
        print $export_result.stderr
        exit 1
    }

    # Create output directory if needed
    let output_dir: string = ($toml_path | path dirname)
    let _ = (paths ensure-dir $output_dir)

    # Save TOML
    (external pipe-to-file $export_result.stdout $toml_path)

    ansi print-success $"TOML config generated: ($toml_path)"
    print ""
    print $"  File size: ((($toml_path) | path exists) and ((^wc -c < $toml_path | str trim) + ' bytes') or 'N/A')"
}
