#!/usr/bin/env bash
# CI Configuration Script
# Auto-generated by dev-system/ci installer
#
# Interactive configuration for CI tools using TypeDialog.
# Uses Nickel format for configuration files.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TYPEDIALOG_CI="${SCRIPT_DIR}"

# Source envrc to load fragment paths and other environment variables
if [[ -f "${TYPEDIALOG_CI}/envrc" ]]; then
    # shellcheck source=/dev/null
    source "${TYPEDIALOG_CI}/envrc"
fi

# Configuration files
FORM_FILE="${TYPEDIALOG_CI}/form.toml"
CONFIG_FILE="${TYPEDIALOG_CI}/config.ncl"

# NCL_TEMPLATE is set by envrc (cascading: local → Tools)
# If not set, use default from Tools
NCL_TEMPLATE="${NCL_TEMPLATE:-${TOOLS_PATH}/dev-system/ci/templates/config.ncl.j2}"

# TypeDialog environment variables (can be overridden)
# Port for web backend (default: 9000)
export TYPEDIALOG_PORT="${TYPEDIALOG_PORT:-9000}"

# Host for web backend (default: localhost)
export TYPEDIALOG_HOST="${TYPEDIALOG_HOST:-localhost}"

# Locale for form localization (default: system locale)
export TYPEDIALOG_LANG="${TYPEDIALOG_LANG:-${LANG:-en_US.UTF-8}}"

# Detect which TypeDialog backend to use (default: web)
BACKEND="${1:-web}"

# Validate backend
case "$BACKEND" in
    cli|tui|web)
        ;;
    *)
        echo "Usage: $0 [cli|tui|web]"
        echo ""
        echo "Launches TypeDialog for interactive CI configuration."
        echo "Backend options:"
        echo "  cli - Command-line interface (simple prompts)"
        echo "  tui - Terminal UI (interactive panels)"
        echo "  web - Web server (browser-based) [default]"
        exit 1
        ;;
esac

# Check if form exists
if [[ ! -f "$FORM_FILE" ]]; then
    echo "Error: Form file not found: $FORM_FILE"
    exit 1
fi

# Create backup if config exists
if [[ -f "$CONFIG_FILE" ]]; then
    BACKUP="${CONFIG_FILE}.$(date +%Y%m%d_%H%M%S).bak"
    cp "$CONFIG_FILE" "$BACKUP"
    echo "ℹ️  Backed up existing config to: $(basename "$BACKUP")"
fi

# Launch TypeDialog with Nickel roundtrip (preserves Nickel format)
echo "🔧 Launching TypeDialog ($BACKEND backend)..."
echo ""

# Show web server info if using web backend
if [[ "$BACKEND" == "web" ]]; then
    echo "🌐 Web server will start on: http://${TYPEDIALOG_HOST}:${TYPEDIALOG_PORT}"
    echo "   (Override with: TYPEDIALOG_PORT=8080 TYPEDIALOG_HOST=0.0.0.0 $0)"
    echo ""
fi

# Build nickel-roundtrip command with optional template
NCL_TEMPLATE_ARG=""
if [[ -f "$NCL_TEMPLATE" ]]; then
    NCL_TEMPLATE_ARG="--ncl-template $NCL_TEMPLATE"
    echo "ℹ️  Using Nickel template: $NCL_TEMPLATE"
fi

case "$BACKEND" in
    cli)
        typedialog nickel-roundtrip "$CONFIG_FILE" "$FORM_FILE" --output "$CONFIG_FILE" $NCL_TEMPLATE_ARG
        ;;
    tui)
        typedialog-tui nickel-roundtrip "$CONFIG_FILE" "$FORM_FILE" --output "$CONFIG_FILE" $NCL_TEMPLATE_ARG
        ;;
    web)
        typedialog-web nickel-roundtrip "$CONFIG_FILE" "$FORM_FILE" --output "$CONFIG_FILE" $NCL_TEMPLATE_ARG
        ;;
esac

EXIT_CODE=$?

if [[ $EXIT_CODE -eq 0 ]]; then
    echo ""
    echo "✅ Configuration saved to: $CONFIG_FILE"
    echo ""
    echo "Next steps:"
    echo "  - Review the configuration: cat $CONFIG_FILE"
    echo "  - Apply CI tools: (run your CI setup command)"
    echo "  - Re-run this script anytime to update: $0"
else
    echo ""
    echo "❌ Configuration cancelled or failed (exit code: $EXIT_CODE)"
    if [[ -f "${CONFIG_FILE}.bak" ]]; then
        echo "   Previous config restored from backup"
    fi
    exit $EXIT_CODE
fi
