# Module: Configuration Context Manager
# Purpose: Manages workspace context, user configuration, and configuration file loading paths.
# Dependencies: None (context utility)

# Context and Workspace Management Engine
# Handles workspace tracking, user context overrides, and configuration value management

use std log

# Get active workspace from user config
# CRITICAL: This replaces get-defaults-config-path
export def get-active-workspace [] {
    let user_config_dir = ([$env.HOME "Library" "Application Support" "provisioning"] | path join)

    if not ($user_config_dir | path exists) {
        return null
    }

    # Load central user config
    let user_config_path = ($user_config_dir | path join "user_config.yaml")

    if not ($user_config_path | path exists) {
        return null
    }

    let user_config = (open $user_config_path)

    # Check if active workspace is set
    if ($user_config.active_workspace == null) {
        null
    } else {
        # Find workspace in list
        let workspace_name = $user_config.active_workspace
        let workspace = ($user_config.workspaces | where name == $workspace_name | first)

        if ($workspace | is-empty) {
            null
        } else {
            {
                name: $workspace.name
                path: $workspace.path
            }
        }
    }
}

# Apply user context overrides with proper priority
export def apply-user-context-overrides [
    config: record
    context: record
] {
    let overrides = ($context | get -o overrides | default {})

    mut result = $config

    # Apply each override if present
    for key in ($overrides | columns) {
        let value = ($overrides | get $key)
        match $key {
            "debug_enabled" => { $result = ($result | upsert debug.enabled $value) }
            "log_level" => { $result = ($result | upsert debug.log_level $value) }
            "metadata" => { $result = ($result | upsert debug.metadata $value) }
            "secret_provider" => { $result = ($result | upsert secrets.provider $value) }
            "kms_mode" => { $result = ($result | upsert kms.mode $value) }
            "kms_endpoint" => { $result = ($result | upsert kms.remote.endpoint $value) }
            "ai_enabled" => { $result = ($result | upsert ai.enabled $value) }
            "ai_provider" => { $result = ($result | upsert ai.provider $value) }
            "default_provider" => { $result = ($result | upsert providers.default $value) }
        }
    }

    # Update last_used timestamp for the workspace
    let workspace_name = ($context | get -o workspace.name | default null)
    if ($workspace_name | is-not-empty) {
        update-workspace-last-used-internal $workspace_name
    }

    $result
}

# Set a configuration value using dot notation
export def set-config-value [
    config: record
    path: string
    value: any
] {
    let path_parts = ($path | split row ".")
    mut result = $config

    if ($path_parts | length) == 1 {
        $result | upsert ($path_parts | first) $value
    } else if ($path_parts | length) == 2 {
        let section = ($path_parts | first)
        let key = ($path_parts | last)
        let section_data = ($result | get -o $section | default {})
        $result | upsert $section ($section_data | upsert $key $value)
    } else if ($path_parts | length) == 3 {
        let section = ($path_parts | first)
        let subsection = ($path_parts | get 1)
        let key = ($path_parts | last)
        let section_data = ($result | get -o $section | default {})
        let subsection_data = ($section_data | get -o $subsection | default {})
        $result | upsert $section ($section_data | upsert $subsection ($subsection_data | upsert $key $value))
    } else {
        # For deeper nesting, use recursive approach
        set-config-value-recursive $result $path_parts $value
    }
}

# Internal helper to update last_used timestamp
def update-workspace-last-used-internal [workspace_name: string] {
    let user_config_dir = ([$env.HOME "Library" "Application Support" "provisioning"] | path join)
    let context_file = ($user_config_dir | path join $"ws_($workspace_name).yaml")

    if ($context_file | path exists) {
        let config = (open $context_file)
        if ($config != null) {
            let updated = ($config | upsert metadata.last_used (date now | format date "%Y-%m-%dT%H:%M:%SZ"))
            $updated | to yaml | save --force $context_file
        }
    }
}

# Recursive helper for deep config value setting
def set-config-value-recursive [
    config: record
    path_parts: list
    value: any
] {
    if ($path_parts | length) == 1 {
        $config | upsert ($path_parts | first) $value
    } else {
        let current_key = ($path_parts | first)
        let remaining_parts = ($path_parts | skip 1)
        let current_section = ($config | get -o $current_key | default {})
        $config | upsert $current_key (set-config-value-recursive $current_section $remaining_parts $value)
    }
}
