# Configuration Export Script
# Converts Nickel config.ncl to service-specific TOML files
# Usage: export-all-configs [workspace_path]
#        export-platform-config <service> [workspace_path]

use ../utils/nickel_processor.nu [ncl-eval-soft]

# Logging functions - not using std/log due to compatibility

# Export all configuration sections from Nickel config
export def export-all-configs [workspace_path?: string] {
  let workspace = if ($workspace_path | is-empty) {
    get-active-workspace
  } else {
    { path: $workspace_path }
  }

  let config_file = $"($workspace.path)/config/config.ncl"

  # Validate that config file exists
  if not ($config_file | path exists) {
    return
  }

  # Create generated directory
  (do { mkdir ($"($workspace.path)/config/generated") } | ignore)

  # Skip verbose output during initialization (controlled by env var)
  let quiet_mode = ($env.PROVISIONING_QUIET_EXPORT? | default "false") == "true"

  if (not $quiet_mode) {
    print $"📥 Exporting configuration from: ($config_file)"
  }

  # Step 1: Typecheck the Nickel file
  let typecheck_result = (do { nickel typecheck $config_file } | complete)
  if $typecheck_result.exit_code != 0 {
    print "❌ Nickel configuration validation failed"
    print $typecheck_result.stderr
    return
  }

  # Step 2: Export to JSON
  let json_output = (ncl-eval-soft $config_file [] null)
  if ($json_output | is-empty) {
    print "❌ Failed to export Nickel to JSON"
    return
  }

  # Step 3: Export workspace section
  if ($json_output | get -o workspace | is-not-empty) {
    print "📝 Exporting workspace configuration"
    $json_output.workspace | to toml | save -f $"($workspace.path)/config/generated/workspace.toml"
  }

  # Step 4: Export provider sections
  if ($json_output | get -o providers | is-not-empty) {
    (do { mkdir $"($workspace.path)/config/generated/providers" } | ignore)

    ($json_output.providers | to json | from json) | transpose name value | each {|provider|
      if ($provider.value | get -o enabled | default false) {
        print $"📝 Exporting provider: ($provider.name)"
        $provider.value | to toml | save -f $"($workspace.path)/config/generated/providers/($provider.name).toml"
      }
    }
  }

  # Step 5: Export platform service sections
  if ($json_output | get -o platform | is-not-empty) {
    (do { mkdir $"($workspace.path)/config/generated/platform" } | ignore)

    ($json_output.platform | to json | from json) | transpose name value | each {|service|
      if ($service.value | type) == 'record' and ($service.value | get -o enabled | is-not-empty) {
        if ($service.value | get enabled) {
          print $"📝 Exporting platform service: ($service.name)"
          $service.value | to toml | save -f $"($workspace.path)/config/generated/platform/($service.name).toml"
        }
      }
    }
  }

  # Skip verbose output during initialization
  let quiet_mode = ($env.PROVISIONING_QUIET_EXPORT? | default "false") == "true"

  if (not $quiet_mode) {
    print "✅ Configuration export complete"
  }
}

# Export a single platform service configuration
export def export-platform-config [service: string, workspace_path?: string] {
  let workspace = if ($workspace_path | is-empty) {
    get-active-workspace
  } else {
    { path: $workspace_path }
  }

  let config_file = $"($workspace.path)/config/config.ncl"

  # Validate that config file exists
  if not ($config_file | path exists) {
    print $"❌ Configuration file not found: ($config_file)"
    return
  }

  # Create generated directory
  (do { mkdir ($"($workspace.path)/config/generated/platform") } | ignore)

  print $"📝 Exporting platform service: ($service)"

  # Step 1: Typecheck the Nickel file
  let typecheck_result = (do { nickel typecheck $config_file } | complete)
  if $typecheck_result.exit_code != 0 {
    print "❌ Nickel configuration validation failed"
    print $typecheck_result.stderr
    return
  }

  # Step 2: Export to JSON and extract platform section
  let json_output = (ncl-eval-soft $config_file [] null)
  if ($json_output | is-empty) {
    print "❌ Failed to export Nickel to JSON"
    return
  }

  # Step 3: Export specific service
  if ($json_output | get -o platform | is-not-empty) and ($json_output.platform | get -o $service | is-not-empty) {
    let service_config = $json_output.platform | get $service
    if ($service_config | type) == 'record' {
      $service_config | to toml | save -f $"($workspace.path)/config/generated/platform/($service).toml"
      print $"✅ Successfully exported: ($service).toml"
    }
  } else {
    print $"❌ Service not found in configuration: ($service)"
  }
}

# Export all provider configurations
export def export-all-providers [workspace_path?: string] {
  let workspace = if ($workspace_path | is-empty) {
    get-active-workspace
  } else {
    { path: $workspace_path }
  }

  let config_file = $"($workspace.path)/config/config.ncl"

  # Validate that config file exists
  if not ($config_file | path exists) {
    print $"❌ Configuration file not found: ($config_file)"
    return
  }

  # Create generated directory
  (do { mkdir ($"($workspace.path)/config/generated/providers") } | ignore)

  print "📥 Exporting all provider configurations"

  # Step 1: Typecheck the Nickel file
  let typecheck_result = (do { nickel typecheck $config_file } | complete)
  if $typecheck_result.exit_code != 0 {
    print "❌ Nickel configuration validation failed"
    print $typecheck_result.stderr
    return
  }

  # Step 2: Export to JSON
  let json_output = (ncl-eval-soft $config_file [] null)
  if ($json_output | is-empty) {
    print "❌ Failed to export Nickel to JSON"
    return
  }

  # Step 3: Export provider sections
  if ($json_output | get -o providers | is-not-empty) {
    ($json_output.providers | to json | from json) | transpose name value | each {|provider|
      # Exporting provider: ($provider.name)
      $provider.value | to toml | save -f $"($workspace.path)/config/generated/providers/($provider.name).toml"
    }
    print "✅ Provider export complete"
  } else {
    print "⚠️ No providers found in configuration"
  }
}

# Validate Nickel configuration without exporting
export def validate-config [workspace_path?: string] {
  let workspace = if ($workspace_path | is-empty) {
    get-active-workspace
  } else {
    { path: $workspace_path }
  }

  let config_file = $"($workspace.path)/config/config.ncl"

  # Validate that config file exists
  if not ($config_file | path exists) {
    print $"❌ Configuration file not found: ($config_file)"
    return { valid: false, error: "Configuration file not found" }
  }

  print $"🔍 Validating configuration: ($config_file)"

  # Run typecheck
  let check_result = (do { nickel typecheck $config_file } | complete)
  if $check_result.exit_code == 0 {
    { valid: true, error: null }
  } else {
    print $"❌ Configuration validation failed"
    print $check_result.stderr
    { valid: false, error: $check_result.stderr }
  }
}

# Show configuration structure without exporting
export def show-config [workspace_path?: string] {
  let workspace = if ($workspace_path | is-empty) {
    get-active-workspace
  } else {
    { path: $workspace_path }
  }

  let config_file = $"($workspace.path)/config/config.ncl"

  # Validate that config file exists
  if not ($config_file | path exists) {
    print $"❌ Configuration file not found: ($config_file)"
    return
  }

  print "📋 Loading configuration structure"

  let json_output = (ncl-eval-soft $config_file [] null)
  if ($json_output | is-not-empty) {
    print ($json_output | to json --indent 2)
  } else {
    print $"❌ Failed to load configuration"
  }
}

# List all configured providers
export def list-providers [workspace_path?: string] {
  let workspace = if ($workspace_path | is-empty) {
    get-active-workspace
  } else {
    { path: $workspace_path }
  }

  let config_file = $"($workspace.path)/config/config.ncl"

  # Validate that config file exists
  if not ($config_file | path exists) {
    print $"❌ Configuration file not found: ($config_file)"
    return
  }

  let config = (ncl-eval-soft $config_file [] null)
  if ($config | is-empty) {
    print $"❌ Failed to list providers"
    return
  }
  if ($config | get -o providers | is-not-empty) {
    print "☁️  Configured Providers:"
    ($config.providers | to json | from json) | transpose name value | each {|provider|
      let status = if ($provider.value | get -o enabled | default false) { "✓ enabled" } else { "✗ disabled" }
      print $"  ($provider.name): ($status)"
    }
  } else {
    print "⚠️ No providers found in configuration"
  }
}

# List all configured platform services
export def list-platform-services [workspace_path?: string] {
  let workspace = if ($workspace_path | is-empty) {
    get-active-workspace
  } else {
    { path: $workspace_path }
  }

  let config_file = $"($workspace.path)/config/config.ncl"

  # Validate that config file exists
  if not ($config_file | path exists) {
    print $"❌ Configuration file not found: ($config_file)"
    return
  }

  let config = (ncl-eval-soft $config_file [] null)
  if ($config | is-empty) {
    print $"❌ Failed to list platform services"
    return
  }
  if ($config | get -o platform | is-not-empty) {
    print "⚙️  Configured Platform Services:"
    ($config.platform | to json | from json) | transpose name value | each {|service|
      if ($service.value | type) == 'record' and ($service.value | get -o enabled | is-not-empty) {
        let status = if ($service.value | get enabled) { "✓ enabled" } else { "✗ disabled" }
        print $"  ($service.name): ($status)"
      }
    }
  } else {
    print "⚠️ No platform services found in configuration"
  }
}

# Helper function to get active workspace
def get-active-workspace [] {
  let user_config_file = if ($nu.os-info.name == "macos") {
    $"($env.HOME)/Library/Application Support/provisioning/user_config.yaml"
  } else {
    $"($env.HOME)/.config/provisioning/user_config.yaml"
  }

  if ($user_config_file | path exists) {
    let open_result = (do { open $user_config_file } | complete)
    if $open_result.exit_code == 0 {
      let user_config = ($open_result.stdout | from yaml)
      if ($user_config | get -o active_workspace | is-not-empty) {
        let ws_name = $user_config.active_workspace
        let ws = $user_config.workspaces | where name == $ws_name | get -o 0
        if ($ws | length) > 0 {
          return { name: $ws.name, path: $ws.path }
        }
      }
    }
  }

  # Fallback to current directory
  { name: "current", path: (pwd) }
}
