# Cache Command Handler
# Domain: Configuration and state cache management

# Cache command handler - Manage configuration caches
export def handle_cache [ops: string, flags: record] {
    use ../../../lib_provisioning/config/cache/simple-cache.nu *

    # Parse cache subcommand
    let parts = if ($ops | is-not-empty) {
        ($ops | str trim | split row " " | where { |x| ($x | is-not-empty) })
    } else {
        []
    }

    let subcommand = if ($parts | length) > 0 { $parts | get 0 } else { "status" }
    let args = if ($parts | length) > 1 { $parts | skip 1 } else { [] }

    # Handle cache commands
    match $subcommand {
        "status" => {
            print ""
            cache-status
            print ""
        }

        "config" => {
            let config_cmd = if ($args | length) > 0 { $args | get 0 } else { "show" }
            match $config_cmd {
                "show" => {
                    print ""
                    let config = (get-cache-config)
                    let cache_base = (($env.HOME? | default "~" | path expand) | path join ".provisioning" "cache" "config")
                    print "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
                    print "📋 Cache Configuration"
                    print "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
                    print ""

                    print "▸ Core Settings:"
                    let enabled = ($config | get --optional enabled | default true)
                    print ("  Enabled: " + ($enabled | into string))
                    print ""

                    print "▸ Cache Location:"
                    print ("  Base Path: " + $cache_base)
                    print ""

                    print "▸ Time-To-Live (TTL) Settings:"
                    let ttl_final = ($config | get --optional ttl_final_config | default "300")
                    let ttl_nickel = ($config | get --optional ttl_nickel | default "1800")
                    let ttl_sops = ($config | get --optional ttl_sops | default "900")
                    print ("  Final Config: " + ($ttl_final | into string) + "s (5 minutes)")
                    print ("  Nickel Compilation: " + ($ttl_nickel | into string) + "s (30 minutes)")
                    print ("  SOPS Decryption: " + ($ttl_sops | into string) + "s (15 minutes)")
                    print "  Provider Config: 600s (10 minutes)"
                    print "  Platform Config: 600s (10 minutes)"
                    print ""

                    print "▸ Security Settings:"
                    print "  SOPS File Permissions: 0600 (owner read-only)"
                    print "  SOPS Directory Permissions: 0700 (owner access only)"
                    print ""

                    print "▸ Validation Settings:"
                    print "  Strict mtime Checking: true (validates all source files)"
                    print ""
                    print "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
                    print ""
                }
                "get" => {
                    if ($args | length) > 1 {
                        let setting = $args | get 1
                        let value = (cache-config-get $setting)
                        if $value != null {
                            print $"($setting) = ($value)"
                        } else {
                            print $"Setting not found: ($setting)"
                        }
                    } else {
                        print "❌ cache config get requires a setting path"
                        print "Usage: provisioning cache config get <path>"
                        exit 1
                    }
                }
                "set" => {
                    if ($args | length) > 2 {
                        let setting = $args | get 1
                        let value = ($args | skip 2 | str join " ")
                        cache-config-set $setting $value
                        print $"✓ Set ($setting) = ($value)"
                    } else {
                        print "❌ cache config set requires setting path and value"
                        print "Usage: provisioning cache config set <path> <value>"
                        exit 1
                    }
                }
                _ => {
                    print $"❌ Unknown cache config subcommand: ($config_cmd)"
                    print ""
                    print "Available cache config subcommands:"
                    print "  show              - Show all cache configuration"
                    print "  get <setting>     - Get specific cache setting"
                    print "  set <key> <val>   - Set cache setting"
                    print ""
                    print "Available settings for get/set:"
                    print "  enabled           - Cache enabled (true/false)"
                    print "  ttl_final_config  - TTL for final config (seconds)"
                    print "  ttl_nickel           - TTL for Nickel compilation (seconds)"
                    print "  ttl_sops          - TTL for SOPS decryption (seconds)"
                    print ""
                    print "Examples:"
                    print "  provisioning cache config show"
                    print "  provisioning cache config get ttl_final_config"
                    print "  provisioning cache config set ttl_final_config 600"
                    exit 1
                }
            }
        }

        "clear" => {
            let cache_type = if ($args | length) > 0 { $args | get 0 } else { "all" }
            cache-clear $cache_type
            print $"✓ Cleared cache: ($cache_type)"
        }

        "list" => {
            let cache_type = if ($args | length) > 0 { $args | get 0 } else { "*" }
            let items = (cache-list $cache_type)
            if ($items | length) > 0 {
                print $"Cache items \(type: ($cache_type)\):"
                $items | each { |item| print $"  ($item)" }
            } else {
                print "No cache items found"
            }
        }

        "help" => {
            print "
Cache Management Commands:

  provisioning cache status                    # Show cache status and statistics
  provisioning cache config show               # Show cache configuration
  provisioning cache config get <setting>      # Get specific cache setting
  provisioning cache config set <setting> <val> # Set cache setting
  provisioning cache clear [type]              # Clear cache (default: all)
  provisioning cache list [type]               # List cached items (default: all)
  provisioning cache help                      # Show this help message

Available settings (for get/set):
  enabled          - Cache enabled (true/false)
  ttl_final_config - TTL for final config (seconds)
  ttl_nickel          - TTL for Nickel compilation (seconds)
  ttl_sops         - TTL for SOPS decryption (seconds)

Examples:
  provisioning cache status
  provisioning cache config get ttl_final_config
  provisioning cache config set ttl_final_config 600
  provisioning cache config set enabled false
  provisioning cache clear nickel
  provisioning cache list
"
        }

        _ => {
            print $"❌ Unknown cache command: ($subcommand)"
            print ""
            print "Available cache commands:"
            print "  status              - Show cache status and statistics"
            print "  config show         - Show cache configuration"
            print "  config get <key>    - Get specific cache setting"
            print "  config set <k> <v>  - Set cache setting"
            print "  clear [type]        - Clear cache (all, nickel, sops, final)"
            print "  list [type]         - List cached items"
            print "  help                - Show this help message"
            print ""
            print "Examples:"
            print "  provisioning cache status"
            print "  provisioning cache config get ttl_final_config"
            print "  provisioning cache config set ttl_final_config 600"
            print "  provisioning cache clear nickel"
            exit 1
        }
    }
}
