#!/usr/bin/env bash
# {{ project_name }} - TypeDialog Nickel Roundtrip Configuration Script
#
# This script integrates TypeDialog forms with Nickel configuration:
# 1. Runs TypeDialog form to collect user input (JSON output)
# 2. Converts JSON to Nickel configuration
# 3. Validates Nickel configuration against schemas
# 4. Merges with defaults and applies type contracts
#
# Usage: ./configure.sh

set -euo pipefail

# Configuration paths
FORM_PATH="{{ form_path }}"
CONFIG_PATH="{{ config_path }}"
TEMPLATE_PATH="{{ template_path }}"
GENERATED_DIR="generated"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Logging functions
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check dependencies
check_dependencies() {
    local missing_deps=()

    if ! command -v typedialog &> /dev/null; then
        missing_deps+=("typedialog")
    fi

    if ! command -v nickel &> /dev/null; then
        missing_deps+=("nickel")
    fi

    if ! command -v jq &> /dev/null; then
        missing_deps+=("jq")
    fi

    if [ ${#missing_deps[@]} -gt 0 ]; then
        log_error "Missing required dependencies: ${missing_deps[*]}"
        log_info "Install with: cargo install typedialog nickel && apt-get install jq"
        exit 1
    fi
}

# Step 1: Run TypeDialog form
run_form() {
    log_info "Running TypeDialog form: ${FORM_PATH}"

    if [ ! -f "${FORM_PATH}" ]; then
        log_error "Form file not found: ${FORM_PATH}"
        exit 1
    fi

    mkdir -p "${GENERATED_DIR}"

    typedialog "${FORM_PATH}" \
        --output-format json \
        --output "${GENERATED_DIR}/user-input.json" || {
        log_error "TypeDialog form execution failed"
        exit 1
    }

    log_success "User input captured: ${GENERATED_DIR}/user-input.json"
}

# Step 2: Convert JSON to Nickel
json_to_nickel() {
    log_info "Converting JSON to Nickel configuration"

    local json_file="${GENERATED_DIR}/user-input.json"
    local nickel_file="${GENERATED_DIR}/config.ncl"

    if [ ! -f "${json_file}" ]; then
        log_error "JSON input file not found: ${json_file}"
        exit 1
    fi

    # Use Nickel's import capability to embed JSON
    cat > "${nickel_file}" <<EOF
# Generated Nickel configuration from TypeDialog form
# Generated at: $(date -u +"%Y-%m-%dT%H:%M:%SZ")

let schemas = import "../schemas/config.ncl" in
let defaults = import "../defaults/config.ncl" in
let validators = import "../validators/config.ncl" in

# User-provided values (from TypeDialog form)
let user_values = $(cat "${json_file}") in

# Merge user values with defaults and apply type contracts
let final_config = std.record.merge defaults user_values in

# Apply validators
let validated_config = validators.validate final_config in

validated_config | schemas.Config
EOF

    log_success "Nickel configuration generated: ${nickel_file}"
}

# Step 3: Validate Nickel configuration
validate_nickel() {
    log_info "Validating Nickel configuration"

    local nickel_file="${GENERATED_DIR}/config.ncl"

    if ! nickel typecheck "${nickel_file}"; then
        log_error "Nickel type checking failed"
        exit 1
    fi

    log_success "Nickel type checking passed"

    # Test evaluation
    if ! nickel export "${nickel_file}" > /dev/null; then
        log_error "Nickel evaluation failed"
        exit 1
    fi

    log_success "Nickel evaluation succeeded"
}

# Step 4: Export to final formats
export_config() {
    log_info "Exporting configuration to final formats"

    local nickel_file="${GENERATED_DIR}/config.ncl"

    # Export to JSON
    nickel export --format json "${nickel_file}" > "${GENERATED_DIR}/config.json"
    log_success "Exported: ${GENERATED_DIR}/config.json"

    # Export to YAML
    nickel export --format yaml "${nickel_file}" > "${GENERATED_DIR}/config.yaml"
    log_success "Exported: ${GENERATED_DIR}/config.yaml"

    # Export to TOML (via JSON)
    if command -v json2toml &> /dev/null; then
        jq -r '.' "${GENERATED_DIR}/config.json" | json2toml > "${GENERATED_DIR}/config.toml"
        log_success "Exported: ${GENERATED_DIR}/config.toml"
    else
        log_warn "json2toml not found, skipping TOML export"
    fi
}

# Main execution
main() {
    log_info "Starting {{ project_name }} configuration"

    check_dependencies
    run_form
    json_to_nickel
    validate_nickel
    export_config

    log_success "Configuration complete!"
    log_info "Generated files in: ${GENERATED_DIR}/"
    log_info "  - config.ncl (Nickel source)"
    log_info "  - config.json (JSON export)"
    log_info "  - config.yaml (YAML export)"
}

main "$@"
