# ╔══════════════════════════════════════════════════════════════════════╗
# ║              Nickel Schema → TypeDialog Form Recipes                 ║
# ║         Generate TOML forms with fragments, conditionals, i18n       ║
# ╚══════════════════════════════════════════════════════════════════════╝

# Generate TOML form from Nickel schema with all features
[doc("Generate TOML form from Nickel schema")]
nickel-to-form SCHEMA OUTPUT_DIR="generated":
    #!/usr/bin/env bash
    set -euo pipefail

    if [ ! -f "{{ SCHEMA }}" ]; then
        echo "Error: Schema file not found: {{ SCHEMA }}"
        exit 1
    fi

    echo "Generating TOML form from {{ SCHEMA }}..."
    mkdir -p "{{ OUTPUT_DIR }}/fragments"
    mkdir -p "{{ OUTPUT_DIR }}/locales/en"
    mkdir -p "{{ OUTPUT_DIR }}/locales/es"

    # Generate main form with fragments, conditionals, i18n
    cargo run --package typedialog -- \
        nickel-to-form "{{ SCHEMA }}" \
        --flatten \
        --groups \
        --fragments \
        --conditionals \
        --i18n \
        --output "{{ OUTPUT_DIR }}"

    echo "✓ Form generated in {{ OUTPUT_DIR }}/"
    echo ""
    echo "Generated files:"
    [ -f "{{ OUTPUT_DIR }}/form.toml" ] && echo "  - {{ OUTPUT_DIR }}/form.toml"
    [ -f "{{ OUTPUT_DIR }}/main_form.toml" ] && echo "  - {{ OUTPUT_DIR }}/main_form.toml"
    [ -d "{{ OUTPUT_DIR }}/fragments" ] && [ "$(ls -A {{ OUTPUT_DIR }}/fragments 2>/dev/null)" ] && \
        echo "  - {{ OUTPUT_DIR }}/fragments/ ($(ls {{ OUTPUT_DIR }}/fragments/*.toml 2>/dev/null | wc -l) files)"
    [ -d "{{ OUTPUT_DIR }}/locales" ] && [ "$(ls -A {{ OUTPUT_DIR }}/locales 2>/dev/null)" ] && \
        echo "  - {{ OUTPUT_DIR }}/locales/ ($(ls -d {{ OUTPUT_DIR }}/locales/* 2>/dev/null | wc -l) locales)"

# Complete workflow: schema → form → execute → Nickel output
[doc("Full workflow: schema → form → results → Nickel")]
nickel-workflow SCHEMA TEMPLATE OUTPUT="config.ncl":
    #!/usr/bin/env bash
    set -euo pipefail

    if [ ! -f "{{ SCHEMA }}" ]; then
        echo "Error: Schema file not found: {{ SCHEMA }}"
        exit 1
    fi

    if [ ! -f "{{ TEMPLATE }}" ]; then
        echo "Error: Template file not found: {{ TEMPLATE }}"
        exit 1
    fi

    TMP_DIR=$(mktemp -d)
    trap "rm -rf $TMP_DIR" EXIT

    TMP_FORM="$TMP_DIR/form.toml"
    TMP_RESULTS="$TMP_DIR/results.json"

    echo "=== Nickel Workflow ==="
    echo ""

    # Step 1: Generate form from schema
    echo "1. Generating TOML form from schema..."
    just nickel::nickel-to-form "{{ SCHEMA }}" "$TMP_DIR" > /dev/null

    # Step 2: Execute form interactively
    echo "2. Executing interactive form..."
    [ -f "$TMP_DIR/main_form.toml" ] && FORM_FILE="$TMP_DIR/main_form.toml" || FORM_FILE="$TMP_DIR/form.toml"

    cargo run --package typedialog -- \
        form "$FORM_FILE" \
        -o "$TMP_RESULTS" || {
        echo "Error: Form execution failed"
        exit 1
    }

    # Step 3: Render template
    echo "3. Rendering Nickel output from template..."
    cargo run --package typedialog -- \
        nickel-template "{{ TEMPLATE }}" "$TMP_RESULTS" \
        -o "{{ OUTPUT }}" || {
        echo "Error: Template rendering failed"
        exit 1
    }

    # Step 4: Validate output
    echo "4. Validating Nickel configuration..."
    nickel typecheck "{{ OUTPUT }}" || {
        echo "Error: Generated Nickel is invalid"
        exit 1
    }

    echo ""
    echo "✓ Workflow complete!"
    echo "  - Nickel configuration written to {{ OUTPUT }}"
    echo ""
    echo "Next steps:"
    echo "  - Review: cat {{ OUTPUT }}"
    echo "  - Export: nickel export {{ OUTPUT }}"

# Preview form generation without writing files
[doc("Preview TOML form without writing")]
nickel-preview SCHEMA:
    #!/usr/bin/env bash
    set -euo pipefail

    if [ ! -f "{{ SCHEMA }}" ]; then
        echo "Error: Schema file not found: {{ SCHEMA }}"
        exit 1
    fi

    echo "Previewing form generation for {{ SCHEMA }}..."
    echo ""

    cargo run --package typedialog -- \
        nickel-to-form "{{ SCHEMA }}" \
        --flatten \
        --groups

# Extract i18n translations only
[doc("Extract i18n from Nickel schema")]
nickel-i18n SCHEMA OUTPUT_DIR="locales":
    #!/usr/bin/env bash
    set -euo pipefail

    if [ ! -f "{{ SCHEMA }}" ]; then
        echo "Error: Schema file not found: {{ SCHEMA }}"
        exit 1
    fi

    echo "Extracting i18n translations from {{ SCHEMA }}..."
    mkdir -p "{{ OUTPUT_DIR }}"

    cargo run --package typedialog -- \
        nickel-to-form "{{ SCHEMA }}" \
        --i18n \
        --output "{{ OUTPUT_DIR }}"

    echo "✓ Translations extracted to {{ OUTPUT_DIR }}/"
    echo ""

    if [ -d "{{ OUTPUT_DIR }}/locales" ]; then
        echo "Generated .ftl files:"
        find "{{ OUTPUT_DIR }}/locales" -name "*.ftl" -type f | sort | while read f; do
            locale=$(basename $(dirname "$f"))
            echo "  - $locale: $f ($(wc -l < "$f") lines)"
        done
    fi

# Roundtrip workflow: .ncl → form → .ncl with preserved validators
[doc("Roundtrip: input.ncl → form → output.ncl (preserves validators)")]
nickel-roundtrip INPUT FORM OUTPUT="output.ncl" VALIDATE="true" VERBOSE="false":
    #!/usr/bin/env bash
    set -euo pipefail

    if [ ! -f "{{ INPUT }}" ]; then
        echo "Error: Input Nickel file not found: {{ INPUT }}"
        exit 1
    fi

    if [ ! -f "{{ FORM }}" ]; then
        echo "Error: Form definition not found: {{ FORM }}"
        exit 1
    fi

    VALIDATE_FLAG=""
    if [ "{{ VALIDATE }}" != "true" ]; then
        VALIDATE_FLAG="--no-validate"
    fi

    VERBOSE_FLAG=""
    if [ "{{ VERBOSE }}" = "true" ]; then
        VERBOSE_FLAG="-v"
    fi

    echo "=== Nickel Roundtrip Workflow ==="
    echo "Input:  {{ INPUT }}"
    echo "Form:   {{ FORM }}"
    echo "Output: {{ OUTPUT }}"
    echo ""

    cargo run --package typedialog -- \
        nickel-roundtrip \
        "{{ INPUT }}" \
        "{{ FORM }}" \
        --output "{{ OUTPUT }}" \
        $VALIDATE_FLAG \
        $VERBOSE_FLAG

# Roundtrip with pre-executed form results (fast iteration)
[doc("Roundtrip from pre-computed form results")]
nickel-roundtrip-from-json INPUT RESULTS OUTPUT="output.ncl":
    #!/usr/bin/env bash
    set -euo pipefail

    if [ ! -f "{{ INPUT }}" ]; then
        echo "Error: Input Nickel file not found: {{ INPUT }}"
        exit 1
    fi

    if [ ! -f "{{ RESULTS }}" ]; then
        echo "Error: Results JSON file not found: {{ RESULTS }}"
        exit 1
    fi

    echo "Rendering Nickel from JSON results..."
    echo "Input:   {{ INPUT }}"
    echo "Results: {{ RESULTS }}"
    echo "Output:  {{ OUTPUT }}"
    echo ""

    # Extract contracts from input and render with results
    # (This is a placeholder - would need a dedicated command in CLI)
    echo "Note: This requires implementation of nickel-render-json command"
    exit 1

# Show nickel recipes help
[doc("Show Nickel integration recipes help")]
help:
    @echo "╔═══════════════════════════════════════════════════════════╗"
    @echo "║     Nickel Integration Recipes                            ║"
    @echo "║     (For Nickel schema → TOML form generation)            ║"
    @echo "╚═══════════════════════════════════════════════════════════╝"
    @echo ""
    @echo "RECIPES:"
    @echo ""
    @echo "  just nickel::nickel-to-form SCHEMA [OUTPUT_DIR]"
    @echo "    Generate TOML form from Nickel schema with fragments,"
    @echo "    conditionals, and i18n extraction."
    @echo "    Default OUTPUT_DIR: generated/"
    @echo ""
    @echo "  just nickel::nickel-workflow SCHEMA TEMPLATE [OUTPUT]"
    @echo "    Complete workflow: schema → form → results → Nickel"
    @echo "    Validates output with 'nickel typecheck'."
    @echo "    Default OUTPUT: config.ncl"
    @echo ""
    @echo "  just nickel::nickel-preview SCHEMA"
    @echo "    Preview form generation without writing files."
    @echo "    Useful for schema validation before full generation."
    @echo ""
    @echo "  just nickel::nickel-i18n SCHEMA [OUTPUT_DIR]"
    @echo "    Extract and generate i18n (.ftl) files only."
    @echo "    Default OUTPUT_DIR: locales/"
    @echo ""
    @echo "  just nickel::nickel-roundtrip INPUT FORM [OUTPUT] [VALIDATE] [VERBOSE]"
    @echo "    Roundtrip workflow with validator preservation:"
    @echo "    input.ncl → form execution → output.ncl"
    @echo "    Preserves validator imports and contract calls."
    @echo "    Default OUTPUT: output.ncl, VALIDATE: true, VERBOSE: false"
    @echo ""
    @echo "EXAMPLES:"
    @echo ""
    @echo "  1. Basic form generation:"
    @echo "     just nickel::nickel-to-form schema.ncl my_form/"
    @echo ""
    @echo "  2. Preview before generating:"
    @echo "     just nickel::nickel-preview examples/07-nickel-generation/schemas/simple.ncl"
    @echo ""
    @echo "  3. Extract i18n only:"
    @echo "     just nickel::nickel-i18n schema.ncl translations/"
    @echo ""
    @echo "  4. Full workflow with template:"
    @echo "     just nickel::nickel-workflow \\"
    @echo "       examples/07-nickel-generation/schemas/simple.ncl \\"
    @echo "       examples/07-nickel-generation/templates/config.ncl.j2 \\"
    @echo "       output_config.ncl"
    @echo ""
    @echo "  5. Roundtrip with validator preservation:"
    @echo "     just nickel::nickel-roundtrip \\"
    @echo "       provisioning/values/example.ncl \\"
    @echo "       provisioning/environment-form.toml \\"
    @echo "       -o output_config.ncl \\"
    @echo "       true true"
    @echo ""
