#!/usr/bin/env nu

# Render Docker Compose Files from Nickel Templates
# Exports Nickel templates to YAML Docker Compose format
# Usage: nu render-docker-compose.nu solo
# Usage: nu render-docker-compose.nu enterprise --output custom-compose.yml

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

export def main [
    mode: string                                          # Mode: solo | multiuser | cicd | enterprise
    --template: string = "platform-stack.yml.ncl"        # Template file name (default: platform-stack.yml.ncl)
    --output: string = ""                                # Output path (default: infrastructure/docker/docker-compose.{mode}.yml)
]: nothing -> nothing {
    # Validate inputs
    paths validate-mode $mode

    # Paths
    let template_path: string = (paths get-template-path ("docker-compose/" + $template))
    let default_output: string = "provisioning/platform/infrastructure/docker/docker-compose." + $mode + ".yml"
    let output_path: string = if ($output | str length) > 0 { $output } else { $default_output }

    # Verify template exists
    if not (external file-exists $template_path) {
        print-warning $"Using default template since custom not found: ($template)"
        # For now, we'll document this as a template that needs to be created
        print-info "Template creation deferred to Phase 9 (Nickel Templates)"
        print ""
        print-info "Placeholder: Would render ($template_path) → ($output_path)"
        exit 0
    }

    print-docker $"Rendering Docker Compose for ($mode) mode"
    print $"  Template: ($template_path)"
    print $"  Output:   ($output_path)"
    print ""

    print-working "Exporting Nickel template to JSON..."

    # Export Nickel template to JSON
    let json_result: record<exit_code: int, stdout: string, stderr: string> = (external run-cmd "nickel" ["export", "--format", "json", $template_path])

    if $json_result.exit_code != 0 {
        print-error "Nickel export failed"
        print $json_result.stderr
        exit 1
    }

    print-success "Nickel exported to JSON"

    print-working "Converting JSON to YAML..."

    # Convert JSON to YAML using yq
    let yaml_result: record<exit_code: int, stdout: string, stderr: string> = do {
        echo $json_result.stdout | ^yq -P
    } | complete

    if $yaml_result.exit_code != 0 {
        print-error "YAML conversion failed"
        print $yaml_result.stderr
        exit 1
    }

    print-success "JSON converted to YAML"

    # Create output directory
    let output_dir: string = ($output_path | path dirname)
    let _ = (paths ensure-dir $output_dir)

    # Save YAML to file
    (external pipe-to-file $yaml_result.stdout $output_path)

    print-success $"Docker Compose generated: ($output_path)"

    print ""
    section "Next Steps"
    next-step "Validate:  docker-compose -f ($output_path) config"
    next-step "Deploy:    docker-compose -f ($output_path) up -d"
    next-step "Status:    docker-compose -f ($output_path) ps"
}
