#!/usr/bin/env nu
# Validate KOGRAL configuration schemas
#
# Usage: nu validate-config.nu [--schema <file>]

def main [
    --schema: string                    # Specific schema to validate
    --schema-dir: string = ".typedialog/kogral"  # Directory containing schemas
] {
    print $"(ansi green_bold)KOGRAL Config Validator(ansi reset)"

    # Phase 1: Discover schemas to validate
    let schemas = if ($schema | is-empty) {
        print "Discovering schemas..."
        let glob_pattern = $"($schema_dir)/**/*.ncl"
        let all_files = (glob $glob_pattern | collect)
        # Filter out library files (contracts, helpers) - they're imported, not standalone configs
        $all_files | where { not ($in | str contains "contracts.ncl") and not ($in | str contains "helpers.ncl") }
    } else {
        if not ($schema | path exists) {
            print $"(ansi red)Error: Schema not found: ($schema)(ansi reset)"
            exit 1
        }
        [$schema]
    }

    let schema_count = ($schemas | length)
    print $"Found ($schema_count) schemas to validate"
    print ""

    # Phase 2: Validate each schema
    mut valid_count = 0
    mut invalid_count = 0

    for schema_file in $schemas {
        let filename = $schema_file | path basename
        print $"Validating ($filename)..."

        # Export schema and check exit status
        let export_result = (nickel export --format json $schema_file | complete)

        if $export_result.exit_code == 0 {
            print $"  (ansi green)✓ Valid(ansi reset)"
            $valid_count = $valid_count + 1
        } else {
            print $"  (ansi red)✗ Invalid(ansi reset)"
            if ($export_result.stderr | str length) > 0 {
                let err_lines = ($export_result.stderr | str trim | split row '\n' | first 3)
                print $"    Error: ($err_lines | str join ' ')"
            }
            $invalid_count = $invalid_count + 1
        }
    }

    # Phase 3: Summary
    print ""
    print $"(ansi cyan_bold)Validation Summary:(ansi reset)"
    print $"  Valid:   ($valid_count)"
    print $"  Invalid: ($invalid_count)"
    print $"  Total:   ($schema_count)"

    if $invalid_count > 0 {
        print ""
        print $"(ansi red)✗ Validation FAILED(ansi reset)"
        exit 1
    } else {
        print ""
        print $"(ansi green_bold)✓ All schemas valid(ansi reset)"
    }
}

main
