#!/usr/bin/env bash
# One finished destructible-tank job -> packed GLBs (healthy + damage), contract check, card, showroom manifest.
# usage: tools/vehicles/finish_tank.sh <job_dir>   exit 0 = carded, 1 = contract errors (see <job>/check.json), 2 = no GLB
set -uo pipefail
J=$(readlink -f "$1"); ROOT=$(cd "$(dirname "$0")/../.." && pwd); cd "$ROOT"
S=$(python3 -c "import json;print(json.load(open('$J/job.json'))['slug'])")
[ -f "$J/$S.glb" ] || [ -f "$J/$S-raw.glb" ] || { echo "$S NO GLB"; exit 2; }
tools/vehicles/pack.sh "$J" || exit 2
# phone texture budget (12 MB decoded, 24 MB over 10 m): over it, pack again from the raw file at 512 px / ORM 256
OVER=$(python3 -c "
import sys; sys.path.insert(0, 'lib'); import glb
m = glb.measure('$J/$S.glb'); print(int(m['gpu_mb_decoded'] > (24 if max(m['size_xyz']) > 10 else 12)))")
[ "$OVER" = 1 ] && { echo "$S over the texture budget: 512 px pack"; VEH_MAX=512 VEH_ORM=256 tools/vehicles/pack.sh "$J" || exit 2; }
python3 tools/vehicles/check_vehicle.py "$J" > "$J/check.json" 2>&1; ok=$?
[ $ok = 0 ] || { echo "$S check FAILED"; exit 1; }
python3 tools/vehicles/import_vehicle.py "$J" && python3 tools/vehicles/manifest.py
