#!/usr/bin/env bash
# Convert JSON to Nickel configuration with schema imports
# Usage: ./json-to-nickel.sh <input.json> [output.ncl]

set -euo pipefail

if [ $# -lt 1 ]; then
    echo "Usage: $0 <input.json> [output.ncl]"
    exit 1
fi

INPUT="$1"
OUTPUT="${2:-${INPUT%.json}.ncl}"

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

if ! command -v jq &> /dev/null; then
    echo "Error: jq command not found"
    echo "Install with: apt-get install jq"
    exit 1
fi

# Generate Nickel file with embedded JSON
cat > "${OUTPUT}" <<EOF
# Generated Nickel configuration from JSON
# Source: ${INPUT}
# Generated at: $(date -u +"%Y-%m-%dT%H:%M:%SZ")

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

# User-provided values
let user_values = $(cat "${INPUT}") in

# Merge with defaults
let final_config = std.record.merge defaults user_values in

final_config | schemas.Config
EOF

echo "Converted: ${OUTPUT}"
echo "Validate with: nickel typecheck ${OUTPUT}"
