#!/usr/bin/env nu
# Provisioning Configuration Script
# Version: 1.0.0
# Guidelines: NuShell 0.109.0+ (@.claude/guidelines/nushell.md applied)
#
# Interactive configuration for provisioning using TypeDialog.
# Updates existing config.ncl in place with Nickel roundtrip.
# Loads environment from .typedialog/provisioning/envrc (like CI does)
#
# Usage:
#   nu configure.nu [web|tui|cli] [--project /path] [--port 9000] [--host localhost]

# Load environment variables from envrc (bash-compatible format)
def load_envrc [envrc_path: path] {
    if not ($envrc_path | path exists) {
        return {}
    }

    let envrc_content = (open $envrc_path)
    let lines = ($envrc_content | lines)

    mut result = {}
    for line in $lines {
        if ($line | str starts-with "export ") {
            let var_expr = ($line | str replace "export " "" | str trim)
            if ($var_expr | str contains "=") {
                let parts = ($var_expr | split row "=" | take 2)
                if ($parts | length) >= 2 {
                    let key = ($parts.0 | str replace '"' "" | str trim)
                    let value = ($parts.1 | str replace '"' "" | str replace "'" "" | str trim)
                    $result = ($result | insert $key $value)
                }
            }
        }
    }
    $result
}

def main [
    --backend: string = "web"           # TypeDialog backend: web, tui, cli
    --project: string = ""              # Project path (default: current directory)
    --port: int = 9000                  # Web server port (web backend only)
    --host: string = "localhost"        # Web server host (web backend only)
] {
    print "🔧 Provisioning Configuration"
    print "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    print ""

    # Validate backend
    if $backend not-in ["web", "tui", "cli"] {
        print "❌ Invalid backend: $backend"
        print ""
        print "Usage: nu configure.nu [web|tui|cli] [--project /path]"
        print ""
        print "Backends:"
        print "  web - Web server (browser-based) [default]"
        print "  tui - Terminal UI (interactive panels)"
        print "  cli - Command-line interface (simple prompts)"
        return
    }

    # Determine project path
    let project_path = if ($project | is-empty) { $env.PWD } else { $project }
    let tools_path = ($env.TOOLS_PATH? | default "/Users/Akasha/Tools")
    let prov_dir = ($project_path | path join ".typedialog" "provisioning")

    # Verify provisioning is installed
    if not ($prov_dir | path exists) {
        print "❌ Error: Provisioning not installed in this project"
        print $"   Expected: ($prov_dir)"
        print ""
        print "Run this first:"
        print $"   nu ($tools_path)/dev-system/provisioning/install.nu --project ($project_path) --interactive"
        return
    }

    let form_path = ($prov_dir | path join "form.toml")
    let config_path = ($prov_dir | path join "config.ncl")
    let envrc_path = ($prov_dir | path join "envrc")

    # Verify form exists
    if not ($form_path | path exists) {
        print "❌ Error: Form file not found"
        print $"   Expected: ($form_path)"
        return
    }

    # Verify config exists (configure.nu is for updates, not initial creation)
    if not ($config_path | path exists) {
        print "❌ Error: Configuration file not found"
        print $"   Expected: ($config_path)"
        print ""
        print "Configuration must be created first via install.nu."
        print "Run this:"
        print $"   nu ($tools_path)/dev-system/provisioning/install.nu --project ($project_path) --interactive --backend ($backend)"
        return
    }

    # Create backup (config.ncl is guaranteed to exist at this point)
    let timestamp = (date now | format date "%Y%m%d_%H%M%S")
    let backup_path = $"($config_path).($timestamp).bak"
    cp $config_path $backup_path
    let backup_name = (basename $backup_path)
    print ("ℹ️  Backed up existing config to: .typedialog/provisioning/" + $backup_name)

    # Load environment from envrc (like CI's configure.sh does)
    let env_from_file = (load_envrc $envrc_path)

    print ("🔧 Launching TypeDialog " + $backend + " backend...")
    print "ℹ️  Environment loaded from: .typedialog/provisioning/envrc"
    print ""

    # Show web server info if using web backend
    if $backend == "web" {
        let stored_host = ($env_from_file.TYPEDIALOG_HOST? | default $host)
        let stored_port = ($env_from_file.TYPEDIALOG_PORT? | default ($port | into string))
        print ("🌐 Web server will start on: http://" + $stored_host + ":" + $stored_port)
        print "   (Override: TYPEDIALOG_PORT=8080 TYPEDIALOG_HOST=0.0.0.0 nu configure.nu)"
        print ""
    }

    # Launch TypeDialog with nickel-roundtrip
    let typedialog_cmd = match $backend {
        "cli" => "typedialog"
        "tui" => "typedialog-tui"
        "web" => "typedialog-web"
        _ => {
            print "❌ Invalid backend"
            return
        }
    }

    # Override port/host from command-line args if provided
    let env_for_typedialog = (
        $env_from_file
        | upsert TYPEDIALOG_PORT ($port | into string)
        | upsert TYPEDIALOG_HOST $host
    )

    print ("Running: " + $typedialog_cmd + " nickel-roundtrip " + $config_path + " " + $form_path + " --output " + $config_path)

    let result = (with-env $env_for_typedialog {
        do {
            ^$typedialog_cmd nickel-roundtrip $config_path $form_path --output $config_path
        } | complete
    })

    if $result.exit_code == 0 {
        print ""
        print "✅ Configuration saved to: .typedialog/provisioning/config.ncl"
        print ""
        print "Next steps:"
        print "  - Review the configuration: cat .typedialog/provisioning/config.ncl"
        print "  - Generate manifests: nu generate.nu"
        print "  - Deploy: docker-compose up -d (or kubectl apply -f k8s/)"
        print ""
        print "To reconfigure anytime: nu configure.nu"
    } else {
        print ""
        let msg = "❌ Configuration cancelled or failed (exit code: " + ($result.exit_code | into string) + ")"
        print $msg
        print ""
        if ($result.stderr | str length) > 0 {
            print "Error details:"
            print $result.stderr
        }
        if ($result.stdout | str length) > 0 {
            print "Output:"
            print $result.stdout
        }
        print ""
        let bak_name = (basename $backup_path)
        print ("   Previous config preserved in backup: " + $bak_name)
    }
}
