#!/bin/bash
# pg_preflight_check.sh — 對單一 target 跑 preflight，輸出 JSON
#
# 用法：
#   pg_preflight_check.sh TARGET
#
# 輸出：{"target":"...","ok":true|false,"detail":"..."}

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=./_lib_pg_apply.sh
source "${SCRIPT_DIR}/_lib_pg_apply.sh"

TARGET="${1:-}"
[[ -z "$TARGET" ]] && { echo "{\"target\":\"\",\"ok\":false,\"detail\":\"missing target\"}"; exit 1; }

if pf_msg=$(pgapply_preflight "$TARGET" 2>&1); then
    detail_esc="passed"
else
    detail_esc="${pf_msg//\\/\\\\}"
    detail_esc="${detail_esc//\"/\\\"}"
    detail_esc="${detail_esc//$'\n'/\\n}"
    printf '{"target":"%s","ok":false,"detail":"%s"}\n' "$TARGET" "$detail_esc"
    exit 0
fi
printf '{"target":"%s","ok":true,"detail":"%s"}\n' "$TARGET" "$detail_esc"
