#!/usr/bin/env nu

# Migrate from old config system to new workspace-based configs
# This script:
# 1. Detects old config.defaults.toml usage
# 2. Creates workspace structure
# 3. Generates config/provisioning.yaml from old config
# 4. Migrates provider settings
# 5. Creates user context

use ../core/nulib/lib_provisioning *

def main [
  --workspace-name: string = "default"  # Name for new workspace
  --workspace-path: string              # Path for workspace (defaults to ~/workspaces/{name})
  --dry-run                             # Show what would be done
  --backup                              # Backup old configs
] {
  print "🔄 Migration to Target-Based Configuration System"
  print "=================================================="
  print ""

  if $dry_run {
    print "⚠️  DRY RUN MODE - No changes will be made"
    print ""
  }

  # 1. Detect old system
  print "Step 1: Detecting old configuration..."
  let old_config_path = "/Users/Akasha/project-provisioning/provisioning/config/config.defaults.toml"

  if not ($old_config_path | path exists) {
    print "✅ No old config found. System may already be migrated."
    return
  }

  print $"   Found: ($old_config_path)"

  # Load old config
  let old_config = (open $old_config_path | from toml)
  print "   ✅ Old config loaded"
  print ""

  # 2. Backup if requested
  if $backup and not $dry_run {
    print "Step 2: Creating backup..."
    let backup_file = $"($old_config_path).backup.(date now | format date '%Y%m%d-%H%M%S')"
    cp $old_config_path $backup_file
    print $"   ✅ Backup created: ($backup_file)"
    print ""
  }

  # 3. Determine workspace path
  let ws_path = if ($workspace_path | is-empty) {
    ([$env.HOME "workspaces" $workspace_name] | path join)
  } else {
    $workspace_path
  }

  print $"Step 3: Target workspace"
  print $"   Name: ($workspace_name)"
  print $"   Path: ($ws_path)"
  print ""

  if $dry_run {
    print "   Would create workspace structure..."
  } else {
    # 4. Create workspace structure
    print "Step 4: Creating workspace..."
    if ($ws_path | path exists) {
      print "   ⚠️  Workspace path already exists"
      let confirm = (input "Continue and merge? [y/N]: ")
      if not (($confirm | str downcase) in ["y" "yes"]) {
        print "   ❌ Migration cancelled"
        return
      }
    }

    # Create directories
    let dirs = [
      $ws_path
      $"($ws_path)/config"
      $"($ws_path)/config/providers"
      $"($ws_path)/config/platform"
      $"($ws_path)/infra"
      $"($ws_path)/.cache"
      $"($ws_path)/.runtime"
    ]

    for dir in $dirs {
      if not ($dir | path exists) {
        mkdir $dir
        print $"   ✅ Created: ($dir)"
      }
    }
    print ""
  }

  # 5. Generate provisioning.yaml
  print "Step 5: Generating provisioning.yaml..."

  let new_config = {
    workspace: {
      name: $workspace_name
      version: "1.0.0"
      created: (date now | format date "%Y-%m-%dT%H:%M:%SZ")
    }
    paths: {
      base: $ws_path
      infra: $"($ws_path)/infra"
      cache: $"($ws_path)/.cache"
      runtime: $"($ws_path)/.runtime"
    }
    core: ($old_config | get -i core | default {version: "1.0.0", name: "provisioning"})
    debug: ($old_config | get -i debug | default {enabled: false, log_level: "info"})
    output: ($old_config | get -i output | default {format: "yaml", file_viewer: "bat"})
    http: ($old_config | get -i http | default {use_curl: false})
    providers: ($old_config | get -i providers | default {active: [], default: "local"})
    secrets: {provider: "sops", sops_enabled: true, kms_enabled: false}
    sops: ($old_config | get -i sops | default {use_sops: true})
    cache: ($old_config | get -i cache | default {enabled: true})
  }

  let config_file = $"($ws_path)/config/provisioning.yaml"

  if $dry_run {
    print "   Would write to: ($config_file)"
    print "   Config preview:"
    print ($new_config | to yaml)
  } else {
    $new_config | to yaml | save --force $config_file
    print $"   ✅ Created: ($config_file)"
  }
  print ""

  # 6. Migrate provider configs
  print "Step 6: Migrating provider configs..."
  let providers = ($old_config | get -i providers | default {} | columns | where $it != "default")

  for provider in $providers {
    print $"   • Migrating ($provider)..."

    let template_file = $"/Users/Akasha/project-provisioning/provisioning/extensions/providers/($provider)/config.defaults.toml"

    if not ($template_file | path exists) {
      print $"     ⚠️  Template not found, skipping"
      continue
    }

    let provider_config_file = $"($ws_path)/config/providers/($provider).toml"

    if $dry_run {
      print $"     Would create: ($provider_config_file)"
    } else {
      let template = (open $template_file)
      let content = (
        $template
        | str replace --all "{{workspace.path}}" $ws_path
        | str replace --all "{{workspace.name}}" $workspace_name
      )
      $content | save $provider_config_file
      print $"     ✅ Created: ($provider_config_file)"
    }
  }
  print ""

  # 7. Create user context
  print "Step 7: Creating user context..."
  let user_config_dir = ([$env.HOME "Library" "Application Support" "provisioning"] | path join)
  let context_file = ($user_config_dir | path join $"ws_($workspace_name).yaml")

  let context = {
    workspace: {
      name: $workspace_name
      path: $ws_path
      active: true
    }
    provisioning: {
      path: "/usr/local/provisioning"
    }
    overrides: {
      debug_enabled: false
      log_level: "info"
    }
    metadata: {
      created: (date now | format date "%Y-%m-%dT%H:%M:%SZ")
      last_used: (date now | format date "%Y-%m-%dT%H:%M:%SZ")
      version: "1.0.0"
    }
  }

  if $dry_run {
    print $"   Would create: ($context_file)"
  } else {
    if not ($user_config_dir | path exists) {
      mkdir $user_config_dir
    }
    $context | to yaml | save --force $context_file
    print $"   ✅ Created: ($context_file)"
  }
  print ""

  # 8. Summary
  print "✅ Migration Complete!"
  print ""
  print "📋 Summary:"
  print $"   Workspace: ($workspace_name)"
  print $"   Path: ($ws_path)"
  print $"   Config: ($config_file)"
  print $"   Context: ($context_file)"
  print ""
  print "🎯 Next Steps:"
  print "   1. Review and customize: ($config_file)"
  print "   2. Configure providers in: ($ws_path)/config/providers/"
  print "   3. Test: provisioning workspace config validate"
  print "   4. If all good, remove old config: ($old_config_path)"
  print ""

  if not $dry_run {
    print $"⚠️  IMPORTANT: Old config is still at ($old_config_path)"
    if $backup {
      print $"   Backup saved at: ($old_config_path).backup.*"
    }
    print "   Remove it manually after verifying migration"
  }
}
