#!/usr/bin/env nu
#
# Workspace LibreCloud - Development Environment Loader
# Usage: nu workspace.nu export | jq
#        nu workspace.nu validate
#        nu workspace.nu typecheck

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

def main [cmd: string = "export"] {
  match $cmd {
    "export" => { workspace-export }
    "validate" => { workspace-validate }
    "typecheck" => { workspace-typecheck }
    _ => {
      print "Unknown command: $cmd"
      print ""
      print "Usage:"
      print "  nu workspace.nu export        - Export workspace configuration as JSON"
      print "  nu workspace.nu validate      - Validate workspace configuration"
      print "  nu workspace.nu typecheck     - Type-check all Nickel files"
      exit 1
    }
  }
}

# Export workspace configuration
def workspace-export [] {
  let root_dir = (pwd)
  let nickel_main = $"($root_dir)/nickel/main.ncl"

  # For development, we create a temporary wrapper that handles imports
  # The workspace entry point uses relative imports which don't work in Nickel
  # So we'll use the provisioning main directly with workspace extensions

  # Read provisioning main (which has all schema definitions)
  let provisioning_path = ($root_dir | path join "../../provisioning/nickel/main.ncl")
  let provisioning = (ncl-eval $provisioning_path [])

  # Build the complete workspace structure by composing configs
  let wuji_main = (ncl-eval-soft ($root_dir | path join "nickel/infra/wuji/main.ncl") [] {})
  let sgoyol_main = (ncl-eval-soft ($root_dir | path join "nickel/infra/sgoyol/main.ncl") [] {})

  # Return aggregated workspace
  {
    provisioning: $provisioning,
    infrastructure: {
      wuji: $wuji_main,
      sgoyol: $sgoyol_main,
    }
  } | to json
}

# Validate workspace configuration syntax
def workspace-validate [] {
  let files = (^find nickel -name "*.ncl" -type f | lines)
  let file_count = ($files | length)

  print $"Validating ($file_count) Nickel files..."

  let errors = (
    $files | each {|file|
      let result = (do --ignore-errors { nickel typecheck $file } | complete)
      if $result.exit_code != 0 {
        {
          file: $file,
          error: $result.stderr,
        }
      }
    } | compact
  )

  if ($errors | is-empty) {
    print "✓ All files validated successfully"
  } else {
    print "✗ Validation errors found:"
    $errors | each {|e| print $"  ($e.file): ($e.error)" }
    exit 1
  }
}

# Type-check all Nickel files
def workspace-typecheck [] {
  let files = (^find nickel -name "*.ncl" -type f | lines)
  let file_count = ($files | length)

  print $"Type-checking ($file_count) Nickel files..."

  $files | each {|file|
    let result = (do --ignore-errors { nickel typecheck $file } | complete)
    if $result.exit_code != 0 {
      print $"  ✗ ($file)"
      print $"    ($result.stderr)"
    } else {
      print $"  ✓ ($file)"
    }
  }
}
