# Configuration Loader for Validation System
# Loads validation rules and settings from TOML configuration files
# Error handling: Guard patterns (no try-catch for field access)

export def load_validation_config [
    config_path?: string
] {
    let default_config_path = ($env.FILE_PWD | path join "validation_config.toml")
    let config_file = if ($config_path | is-empty) {
        $default_config_path
    } else {
        $config_path
    }

    if not ($config_file | path exists) {
        error make {
            msg: $"Validation configuration file not found: ($config_file)"
            span: (metadata $config_file).span
        }
    }

    let config = (open $config_file)

    # Validate configuration structure
    validate_config_structure $config

    $config
}

export def load_rules_from_config [
    config: record
    context?: record
] {
    let base_rules = ($config.rules | default [])

    # Load extension rules if extensions are configured
    # Guard: Check if extensions field exists
    let extension_rules = if ("extensions" in ($config | columns)) {
        load_extension_rules $config.extensions
    } else {
        []
    }

    # Combine base and extension rules
    let all_rules = ($base_rules | append $extension_rules)

    # Filter rules based on context (provider, taskserv, etc.)
    let filtered_rules = if ($context | is-not-empty) {
        filter_rules_by_context $all_rules $config $context
    } else {
        $all_rules
    }

    # Sort rules by execution order
    $filtered_rules | sort-by execution_order
}

export def load_extension_rules [
    extensions_config: record
] {
    mut extension_rules = []

    let rule_paths = ($extensions_config.rule_paths | default [])
    let rule_patterns = ($extensions_config.rule_file_patterns | default ["*_validation_rules.toml"])

    for path in $rule_paths {
        if ($path | path exists) {
            for pattern in $rule_patterns {
                let rule_files = (glob ($path | path join $pattern))

                for rule_file in $rule_files {
                    let load_result = (do {
                        let custom_config = (open $rule_file)
                        let custom_rules = ($custom_config.rules | default [])
                        $custom_rules
                    } | complete)

                    if $load_result.exit_code != 0 {
                        print $"⚠️  Warning: Failed to load extension rules from ($rule_file): ($load_result.stderr)"
                    } else {
                        $extension_rules = ($extension_rules | append $load_result.stdout)
                    }
                }
            }
        }
    }

    $extension_rules
}

export def filter_rules_by_context [
    rules: list
    config: record
    context: record
] {
    # Guard: Check if context fields exist
    let provider = if ("provider" in ($context | columns)) { $context | get provider } else { null }
    let taskserv = if ("taskserv" in ($context | columns)) { $context | get taskserv } else { null }
    let infra_type = if ("infra_type" in ($context | columns)) { $context | get infra_type } else { null }

    mut filtered_rules = $rules

    # Filter by provider if specified
    if ($provider | is-not-empty) {
        # Guard: Check if providers section and provider field exist
        let provider_config = if ("providers" in ($config | columns)) and ($provider in ($config.providers | columns)) {
            $config.providers | get $provider
        } else {
            null
        }
        if ($provider_config | is-not-empty) {
            let enabled_rules = ($provider_config.enabled_rules | default [])
            if ($enabled_rules | length) > 0 {
                $filtered_rules = ($filtered_rules | where {|rule| $rule.id in $enabled_rules})
            }
        }
    }

    # Filter by taskserv if specified
    if ($taskserv | is-not-empty) {
        # Guard: Check if taskservs section and taskserv field exist
        let taskserv_config = if ("taskservs" in ($config | columns)) and ($taskserv in ($config.taskservs | columns)) {
            $config.taskservs | get $taskserv
        } else {
            null
        }
        if ($taskserv_config | is-not-empty) {
            let enabled_rules = ($taskserv_config.enabled_rules | default [])
            if ($enabled_rules | length) > 0 {
                $filtered_rules = ($filtered_rules | where {|rule| $rule.id in $enabled_rules})
            }
        }
    }

    # Filter by enabled status
    $filtered_rules | where {|rule| ($rule.enabled | default true)}
}

export def get_rule_by_id [
    rule_id: string
    config: record
] {
    let rules = (load_rules_from_config $config)
    let rule = ($rules | where id == $rule_id | first)

    if ($rule | is-empty) {
        error make {
            msg: $"Rule not found: ($rule_id)"
        }
    }

    $rule
}

export def get_validation_settings [
    config: record
] {
    $config.validation_settings | default {
        default_severity_filter: "warning"
        default_report_format: "md"
        max_concurrent_rules: 4
        progress_reporting: true
        auto_fix_enabled: true
    }
}

export def get_execution_settings [
    config: record
] {
    $config.execution | default {
        rule_groups: ["syntax", "compilation", "schema", "security", "best_practices", "compatibility"]
        rule_timeout: 30
        file_timeout: 10
        total_timeout: 300
        parallel_files: true
        max_file_workers: 8
    }
}

export def get_performance_settings [
    config: record
] {
    $config.performance | default {
        max_file_size: 10
        max_total_size: 100
        max_memory_usage: "512MB"
        enable_caching: true
        cache_duration: 3600
    }
}

export def get_ci_cd_settings [
    config: record
] {
    $config.ci_cd | default {
        exit_codes: { passed: 0, critical: 1, error: 2, warning: 3, system_error: 4 }
        minimal_output: true
        no_colors: true
        structured_output: true
        ci_report_formats: ["yaml", "json"]
    }
}

export def validate_config_structure [
    config: record
] {
    # Validate required sections exist
    let required_sections = ["validation_settings", "rules"]

    for section in $required_sections {
        # Guard: Check if section field exists
        if not ($section in ($config | columns)) {
            error make {
                msg: $"Missing required configuration section: ($section)"
            }
        }
    }

    # Validate rules structure
    let rules = ($config.rules | default [])
    for rule in $rules {
        validate_rule_structure $rule
    }
}

export def validate_rule_structure [
    rule: record
] {
    let required_fields = ["id", "name", "category", "severity", "validator_function"]

    for field in $required_fields {
        # Guard: Check if field exists in rule
        if not ($field in ($rule | columns)) {
            error make {
                msg: $"Rule ($rule.id | default 'unknown') missing required field: ($field)"
            }
        }
    }

    # Validate severity values
    let valid_severities = ["info", "warning", "error", "critical"]
    if ($rule.severity not-in $valid_severities) {
        error make {
            msg: $"Rule ($rule.id) has invalid severity: ($rule.severity). Valid values: ($valid_severities | str join ', ')"
        }
    }
}

export def create_rule_context [
    rule: record
    global_context: record
] {
    $global_context | merge {
        current_rule: $rule
        rule_timeout: ($rule.timeout | default 30)
        auto_fix_enabled: (($rule.auto_fix | default false) and ($global_context.fix_mode | default false))
    }
}
