#!/bin/bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
CONFIG_FILE="$PROJECT_ROOT/config.yaml"

usage() {
    cat <<EOF
Usage: $(basename "$0") [--help]

Generate config.yaml from environment variables.
Sources .env from project root if present.
EOF
    exit 0
}

[[ "${1:-}" == "--help" ]] && usage

if [[ -f "$PROJECT_ROOT/.env" ]]; then
    set -a
    source "$PROJECT_ROOT/.env"
    set +a
fi

required_vars=(
    AZAION_API_URL AZAION_API_EMAIL AZAION_API_PASSWORD
    RABBITMQ_HOST RABBITMQ_PORT RABBITMQ_USER RABBITMQ_PASSWORD RABBITMQ_QUEUE_NAME
    AZAION_ROOT_DIR
)

missing=()
for var in "${required_vars[@]}"; do
    if [[ -z "${!var:-}" ]]; then
        missing+=("$var")
    fi
done

if [[ ${#missing[@]} -gt 0 ]]; then
    echo "ERROR: Missing required environment variables:"
    printf '  %s\n' "${missing[@]}"
    echo "Set them in .env or export them before running."
    exit 1
fi

cat > "$CONFIG_FILE" <<YAML
api:
  url: '${AZAION_API_URL}'
  email: '${AZAION_API_EMAIL}'
  password: '${AZAION_API_PASSWORD}'

queue:
  host: '${RABBITMQ_HOST}'
  port: ${RABBITMQ_PORT}
  consumer_user: '${RABBITMQ_USER}'
  consumer_pw: '${RABBITMQ_PASSWORD}'
  name: '${RABBITMQ_QUEUE_NAME}'

dirs:
  root: '${AZAION_ROOT_DIR}'
  data: '${AZAION_DATA_DIR:-data}'
  data_seed: '${AZAION_DATA_SEED_DIR:-data-seed}'
  data_deleted: '${AZAION_DATA_DELETED_DIR:-data_deleted}'

training:
  model: '${TRAINING_MODEL:-yolo26m.pt}'
  epochs: ${TRAINING_EPOCHS:-120}
  batch: ${TRAINING_BATCH_SIZE:-11}
  imgsz: ${TRAINING_IMGSZ:-1280}
  save_period: ${TRAINING_SAVE_PERIOD:-1}
  workers: ${TRAINING_WORKERS:-24}

export:
  onnx_imgsz: ${EXPORT_ONNX_IMGSZ:-1280}
YAML

echo "Generated $CONFIG_FILE"
