#!/usr/bin/env nu
# Infrastructure-from-Code → Orchestrator Integration
# Generates and submits deployment workflows based on IaC analysis

def main [
  path?: string                    # Project path
  --org: string = "default"        # Organization name
  --infra: string = "default"      # Infrastructure target
  --orchestrator-url: string       # Orchestrator URL
  --monitor                        # Monitor execution
  --verbose (-v)                   # Verbose output
  --dry-run                        # Preview without executing
  --debug (-x)                     # Debug output
] {
  let project_path = ($path | default ".")

  # Validate path exists
  if not ($project_path | path exists) {
    print -e $"❌ Path not found: ($project_path)"
    return
  }

  if $debug {
    print $"🔍 Starting orchestration from IaC"
    print $"   Project: ($project_path)"
    print $"   Organization: ($org)"
    print $"   Infrastructure: ($infra)"
    print ""
  }

  # Load the integration module (use absolute path for parse-time constant)
  # This assumes the provisioning directory is at a known location
  use /Users/Akasha/project-provisioning/provisioning/core/nulib/lib_provisioning/integration/iac_orchestrator.nu *

  # Determine orchestrator URL
  let orch_url = if ($orchestrator_url | is-not-empty) {
    $orchestrator_url
  } else if ($env.ORCHESTRATOR_URL? | is-not-empty) {
    $env.ORCHESTRATOR_URL
  } else {
    "http://localhost:8080"
  }

  # Run the orchestration pipeline
  let result = (orchestrate-from-iac $project_path --org $org --infra $infra --orchestrator-url $orch_url --verbose=$verbose --dry-run=$dry_run)

  # Handle results
  if ($result.status == "error") {
    print -e $"❌ Error at stage '($result.stage)': ($result.message)"
    exit 1
  } else if ($result.status == "dry-run") {
    print "✅ Dry-run completed successfully"
    print "   No changes were applied"
  } else if ($result.status == "success") {
    print "✅ Orchestration completed successfully"
    if ($result.workflow_id? | default "" | is-not-empty) {
      print $"   Workflow ID: ($result.workflow_id)"
    }
  } else if ($result.status == "completed") {
    print "✅ Deployment completed"
    if $verbose {
      print "   Status: ($result.status)"
      let msg = ($result.message? | default "N/A")
      print "   Message: ($msg)"
    }
  } else {
    print "⚠️  Orchestration status: ($result.status)"
    if ($result.message? | default "" | is-not-empty) {
      print "   Message: ($result.message)"
    }
  }

  print ""
}

export def "main orchestrate info" [] {
  print "Infrastructure-from-Code → Orchestrator Integration"
  print "Generates deployment workflows from IaC analysis"
}
