#!/usr/bin/env bash
# T-03 — Build a media pipeline (companion driver)
# Stages a photo + clip in the CDN, derives an image thumbnail and a trimmed
# clip, caches the derivative manifest in memcache, then kills and restarts
# memcache to prove the pipeline survives cache loss.
set -uo pipefail
source /tmp/inaya_env.sh
export INAYA_LABS_ENVIRONMENT=local

export AUTH_URL="http://127.0.0.1:40004"
export CDN_URL="http://127.0.0.1:40040"
export IMG_URL="http://127.0.0.1:40030"
export VID_URL="http://127.0.0.1:40160"
export MEM_URL="http://127.0.0.1:40011"
export CDN_ROOT="${INAYA_LABS_CDN_SHARED_STORAGE_PATH:-/tmp/inaya-cdn-storage}"
export VID_OUT="${INAYA_LABS_VIDEO_OUTPUT_DIR:-/tmp/t03-video-output}"
export INAYA_API_KEY="$INAYA_LABS_API_KEY"
export INAYA_APP_KEY="$INAYA_LABS_APP_KEY"
export TENANT_ID="${TENANT_ID:-qa-tenant-t02}"
cd "$(dirname "$0")/../../../../.."

KEYS=(-H "x-api-key: ${INAYA_API_KEY}" -H "x-client-app-key: ${INAYA_APP_KEY}")
sign_in() {
  curl -sf -X POST "${AUTH_URL}/v3/auth/qa/login" "${KEYS[@]}" \
    -H "Content-Type: application/json" \
    -d "{\"device_id\": \"t03-device-01\", \"locale\": \"en-US\", \"tenant_id\": \"${TENANT_ID}\", \"username\": \"$1\"}" \
    | python3 -c 'import json,sys; print(json.load(sys.stdin)["token"])'
}
TOKEN=$(sign_in t03-priya)
echo "═══ T-03 media pipeline · tenant ${TENANT_ID} ═══"

# 1. stage + verify round-trip
python3 - <<'EOF'
from PIL import Image
img = Image.new("RGB", (1200, 800), (30, 90, 160))
for x in range(0, 1200, 100):
    for y in range(0, 800, 100):
        img.putpixel((x, y), (255, 200, 40))
img.save("/tmp/t03-hero.png")
EOF
curl -sf -o /dev/null -X POST "${CDN_URL}/v3/cdn/files/upload?overwrite=true" \
  -H "Authorization: Bearer ${TOKEN}" "${KEYS[@]}" \
  -F "path=t03/hero.png" -F "file=@/tmp/t03-hero.png"
DL_TOKEN=$(curl -sf -X POST "${CDN_URL}/v3/cdn/files/token" \
  -H "Authorization: Bearer ${TOKEN}" "${KEYS[@]}" \
  -H "Content-Type: application/json" -d '{"path": "t03/hero.png"}' \
  | python3 -c 'import json,sys; print(json.load(sys.stdin)["token"])')
curl -sf "${CDN_URL}/v3/cdn/files/download?token=${DL_TOKEN}" \
  -H "Authorization: Bearer ${TOKEN}" "${KEYS[@]}" -o /tmp/t03-download.png
cmp /tmp/t03-hero.png /tmp/t03-download.png \
  && echo "✔ checkpoint 1 — staged asset downloads byte-identical via token"

# 2. image derivative
SRC=$(find "${CDN_ROOT}/files" -name "hero.png" | head -1)
curl -sf -o /tmp/t03-thumb.png -X POST "${IMG_URL}/v3/images/resize" \
  -H "Authorization: Bearer ${TOKEN}" "${KEYS[@]}" \
  -H "Content-Type: application/json" \
  -d "{\"source_path\": \"${SRC}\", \"tenant_id\": \"${TENANT_ID}\", \"mode\": \"Single\", \"width\": 300, \"height\": 200}"
python3 -c "from PIL import Image; s=Image.open('/tmp/t03-thumb.png').size; assert s==(300,200), s"
curl -sf -o /dev/null -X POST "${CDN_URL}/v3/cdn/files/upload?overwrite=true" \
  -H "Authorization: Bearer ${TOKEN}" "${KEYS[@]}" \
  -F "path=t03/hero-thumb.png" -F "file=@/tmp/t03-thumb.png"
echo "✔ checkpoint 2 — thumbnail derived at 300x200 and staged back in the CDN"

# 3. video derivative (async job)
ffmpeg -y -loglevel error \
  -f lavfi -i testsrc=duration=6:size=320x240:rate=10 -pix_fmt yuv420p \
  /tmp/t03-clip.mp4
curl -sf -o /dev/null -X POST "${CDN_URL}/v3/cdn/files/upload?overwrite=true" \
  -H "Authorization: Bearer ${TOKEN}" "${KEYS[@]}" \
  -F "path=t03/clip.mp4" -F "file=@/tmp/t03-clip.mp4"
VID_SRC=$(find "${CDN_ROOT}/files" -name "clip.mp4" | head -1)
JOB_ID=$(curl -sf -X POST "${VID_URL}/v3/video/trim" \
  -H "Authorization: Bearer ${TOKEN}" "${KEYS[@]}" \
  -H "Content-Type: application/json" \
  -d "{\"source_path\": \"${VID_SRC}\", \"tenant_id\": \"${TENANT_ID}\", \"mode\": \"segment\", \"in_point\": \"00:00:01\", \"out_point\": \"00:00:04\"}" \
  | python3 -c 'import json,sys; print(json.load(sys.stdin)["id"])')
OUT_FILE="${VID_OUT}/${TENANT_ID}/${JOB_ID}.mp4"
for i in $(seq 1 24); do
  [ -f "${OUT_FILE}" ] && break
  sleep 5
done
test -f "${OUT_FILE}" || { echo "job never produced output"; exit 1; }
DUR=$(ffprobe -v error -show_entries format=duration -of csv=p=0 "${OUT_FILE}")
python3 -c "d=float('${DUR}'); assert 0 < d < 6, d"
echo "✔ checkpoint 3 — trimmed clip is ${DUR}s (source was 6.0s, job ${JOB_ID:0:12}…)"

# 4. cache the derivative manifest
MANIFEST="[{\"kind\":\"thumb\",\"path\":\"t03/hero-thumb.png\",\"width\":300,\"height\":200},{\"kind\":\"clip-trim\",\"path\":\"video-output/${JOB_ID}.mp4\",\"in\":\"00:00:01\",\"out\":\"00:00:04\"}]"
python3 - "$MANIFEST" <<'EOF' > /tmp/t03-manifest-body.json
import json, sys
print(json.dumps({"key": "t03:manifest:hero", "value": sys.argv[1], "ttl_in_seconds": 3600}))
EOF
curl -sf -o /dev/null -X POST "${MEM_URL}/v3/mem-cache/add/${TENANT_ID}" \
  -H "Authorization: Bearer ${TOKEN}" "${KEYS[@]}" \
  -H "Content-Type: application/json" --data-binary @/tmp/t03-manifest-body.json
curl -sf "${MEM_URL}/v3/mem-cache/get/${TENANT_ID}/t03:manifest:hero" \
  -H "Authorization: Bearer ${TOKEN}" "${KEYS[@]}" | grep -q "hero-thumb.png" \
  && echo "✔ checkpoint 4 — manifest round-trips with both derivatives listed"

# 5. failure injection: kill memcache, prove the pipeline survives
pkill -x memcache-service && echo "   memcache killed"
sleep 1
curl -s --max-time 5 -o /dev/null "${MEM_URL}/v3/mem-cache/get/${TENANT_ID}/t03:manifest:hero" \
  -H "Authorization: Bearer ${TOKEN}" "${KEYS[@]}" \
  || echo "   get during outage: connection refused (fails loudly)"
curl -sf -o /dev/null "${CDN_URL}/v3/cdn/files/download?token=${DL_TOKEN}" \
  -H "Authorization: Bearer ${TOKEN}" "${KEYS[@]}" \
  && echo "✔ checkpoint 5a — cache outage fails loudly; CDN unaffected"
source /tmp/inaya_env.sh; export INAYA_LABS_ENVIRONMENT=local
nohup "$(pwd)/target/debug/memcache-service" > /tmp/memcache-service.log 2>&1 &
sleep 2
CODE=$(curl -s -o /dev/null -w "%{http_code}" "${MEM_URL}/v3/mem-cache/get/${TENANT_ID}/t03:manifest:hero" \
  -H "Authorization: Bearer ${TOKEN}" "${KEYS[@]}")
test "${CODE}" = "404" && echo "   cache restarted empty (HTTP 404) — expected"
curl -sf -o /dev/null -X POST "${MEM_URL}/v3/mem-cache/add/${TENANT_ID}" \
  -H "Authorization: Bearer ${TOKEN}" "${KEYS[@]}" \
  -H "Content-Type: application/json" --data-binary @/tmp/t03-manifest-body.json
curl -sf "${MEM_URL}/v3/mem-cache/get/${TENANT_ID}/t03:manifest:hero" \
  -H "Authorization: Bearer ${TOKEN}" "${KEYS[@]}" | grep -q "hero-thumb.png" \
  && echo "✔ checkpoint 5b — manifest re-derivable after cache restart"

echo "═══ T-03 complete ═══"
