#!/usr/bin/env nu

# Interactive Configuration Wizard
# Uses TypeDialog nickel-roundtrip pattern for interactive config editing
# Supports multiple backends: cli, tui, web
# Usage: nu configure.nu orchestrator solo
# Usage: nu configure.nu control-center multiuser --backend tui
# Usage: nu configure.nu mcp-server cicd --backend web

use ansi.nu
use external.nu
use paths.nu

export def main [
    service: string               # Service: orchestrator | control-center | mcp-server | vault-service | extension-registry | rag | ai-service | provisioning-daemon
    mode: string                  # Mode: solo | multiuser | cicd | enterprise
    --backend: string = "web"     # TypeDialog backend: cli | tui | web (default: web)
]: nothing -> nothing {
    # Validate inputs
    paths validate-service $service
    paths validate-mode $mode
    paths validate-backend $backend

    # Paths
    let form_path: string = (paths get-form-path $service)
    let config_path: string = (paths get-value-path $service $mode)
    let template_path: string = (paths get-template-path ($service + "-config.ncl.j2"))

    # Verify form exists
    paths assert-file-exists $form_path

    ansi print-progress $"Launching TypeDialog wizard for ($service) in ($mode) mode"
    print $"  Backend:  ($backend)"
    print $"  Form:     ($form_path)"
    print $"  Config:   ($config_path)"
    print $"  Template: ($template_path)"
    print ""

    # Check if config already exists (to load as defaults)
    let config_exists: bool = (external file-exists $config_path)

    if $config_exists {
        ansi print-info "Loading existing config as defaults"
    } else {
        ansi print-warning "No existing config, using form defaults"
    }

    print ""

    # Ensure values directory exists
    let values_dir: string = (paths ensure-dir (paths values-path))

    # Build TypeDialog command with nickel-roundtrip pattern
    let cmd_args: list<string> = if $config_exists {
        # Load existing config, allow editing, save updated config with template
        ["nickel-roundtrip", $config_path, $form_path, "--output", $config_path, "--template", $template_path]
    } else {
        # Create new config from form with template
        ["nickel-roundtrip", $form_path, "--output", $config_path, "--template", $template_path]
    }

    ansi print-working "Starting TypeDialog editor (backend: $backend)..."

    # Launch TypeDialog
    let result: record<exit_code: int, stdout: string, stderr: string> = (external run-typedialog $backend $cmd_args)

    if $result.exit_code != 0 {
        ansi print-error "TypeDialog editor failed or was cancelled"
        print $result.stderr
        exit 1
    }

    # Verify config was created/updated
    if not (external file-exists $config_path) {
        ansi print-error "Config file was not created"
        exit 1
    }

    ansi print-success $"Configuration saved: ($config_path)"

    # Validate the generated config
    ansi print-validate "Validating generated Nickel config..."
    let validate_result: record<exit_code: int, stdout: string, stderr: string> = (external run-cmd "nickel" ["typecheck", $config_path])

    if $validate_result.exit_code != 0 {
        ansi print-error "Generated config failed validation"
        print $validate_result.stderr
        print ""
        ansi print-warning "Your edits may need adjustment. Edit manually at: ($config_path)"
        exit 1
    }

    ansi print-success "Config validation passed"

    print ""
    ansi section "Next Steps"
    ansi next-step $"Validate:  nu scripts/validate-config.nu ($config_path)"
    ansi next-step $"Generate:  nu scripts/generate-configs.nu ($service) ($mode)"
    ansi next-step $"Build:     cargo build -p ($service)"
    ansi next-step $"Run:       cargo run -p ($service) -- --config provisioning/config/runtime/generated/($service).($mode).toml"
}
