#!/bin/bash
# Real: single-primary NVConfig bulk apply.
set -euo pipefail

source "$(dirname "$0")/_lib.sh"
trace "$@"

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
source "$SCRIPT_DIR/_value_maps.sh" 2>/dev/null || source "$SCRIPT_DIR/../_value_maps.sh"

TARGET="$1"; shift
BDF=$(bdf_from_target "$TARGET")
WITH_DEFAULT=false
FORCE=false

EXTRA_ARGS=()
SET_ARGS=()
while [[ $# -gt 0 ]]; do
    case "$1" in
        --with-default|--with_default)
            WITH_DEFAULT=true
            EXTRA_ARGS+=(--with_default)
            shift
            ;;
        --force)
            FORCE=true
            EXTRA_ARGS+=(--force)
            shift
            ;;
        --)
            shift
            break
            ;;
        *)
            PARAM="${1%%=*}"
            VALUE="${1#*=}"
            MAPPED="${FWD[$PARAM:$VALUE]:-$VALUE}"
            SET_ARGS+=("${PARAM}=${MAPPED}")
            shift
            ;;
    esac
done

if [[ ${#SET_ARGS[@]} -eq 0 ]]; then
    echo '{"status":"error","error_msg":"No NVConfig parameters to apply"}'
    exit 1
fi

# Capture combined stdout+stderr: mlxconfig writes its failure reason to either
# stream depending on the error, so mlxconfig_error_reason needs both.
if OUT=$("${MLXCONFIG_BIN:-mlxconfig}" -d "$BDF" "${EXTRA_ARGS[@]}" -y set "${SET_ARGS[@]}" 2>&1); then
    RC=0
else
    RC=$?
fi

if [[ $RC -eq 0 ]]; then
    /usr/bin/python3 - "$TARGET" "$WITH_DEFAULT" "$FORCE" "${SET_ARGS[@]}" <<'PY'
import json
import sys

target, with_default, force, *params = sys.argv[1:]
print(json.dumps({
    "status": "ok",
    "primary-target": target,
    "compiled-count": len(params),
    "requires-reset": True,
    "with-default": with_default == "true",
    "force": force == "true",
    "params": params,
}, separators=(",", ":")))
PY
else
    ERR_MSG=$(mlxconfig_error_reason "$OUT" | sed 's/"/\\"/g')
    echo "{\"status\":\"error\",\"error_msg\":\"mlxconfig bulk set failed (rc=$RC): ${ERR_MSG}\"}"
    exit 1
fi
