#!/bin/bash
# chip-fetcher 0.1.3 demo — per-scene recorder
set -u
SESS="chip-fetcher-demo"
TAB="tab-1"
DEMO=/tmp/cf-demo
mkdir -p "$DEMO"/{raw,clips}

post_act() {
  curl -s -X POST http://127.0.0.1:8780/api/activity \
    -H "Content-Type: application/json" \
    -d "{\"mpn\":\"$1\",\"stage\":\"$2\"}" > /dev/null
}

eval_pup() {
  local expr="$1"
  adom-desktop browser_eval "$(python3 -c "import sys, json; print(json.dumps({'sessionId':'$SESS','tabId':'$TAB','expr':sys.argv[1]}))" "$expr")" >/dev/null 2>&1
}

focus_pup() {
  adom-desktop browser_focus_window "{\"sessionId\":\"$SESS\"}" >/dev/null 2>&1
}

record_scene() {
  local id="$1"; local duration="$2"; shift 2
  echo "  scene $id ($duration s): $*"
  focus_pup; sleep 0.5
  post_act "DEMO" "$id"
  # Start nudge loop in background to keep compositor active
  ( for i in $(seq 1 $((duration * 5))); do
      eval_pup 'document.documentElement.style.setProperty("--nudge", Math.random())'
      sleep 0.2
    done ) &
  local NPID=$!
  # Start recording
  local START=$(adom-desktop browser_record_start "{\"sessionId\":\"$SESS\",\"tabId\":\"$TAB\",\"fps\":15,\"quality\":75}" 2>&1)
  local RID=$(echo "$START" | python3 -c "import sys,json; print(json.load(sys.stdin).get('recordingId',''))")
  # Run scene actions in foreground
  "$@"
  # Stop recording
  local STOP=$(adom-desktop browser_record_stop "{\"sessionId\":\"$SESS\",\"tabId\":\"$TAB\",\"recordingId\":\"$RID\"}" 2>&1)
  kill $NPID 2>/dev/null; wait $NPID 2>/dev/null
  local FILEPATH=$(echo "$STOP" | python3 -c "import sys,json; print(json.load(sys.stdin).get('filePath',''))")
  local FPS=$(echo "$STOP" | python3 -c "import sys,json; print(round(json.load(sys.stdin).get('fpsActual',0),1))")
  local FRAMES=$(echo "$STOP" | python3 -c "import sys,json; print(json.load(sys.stdin).get('frameCount',0))")
  echo "    captured $FRAMES frames at $FPS fps -> $FILEPATH"
  # Pull from Windows
  adom-desktop pull_file "{\"filePaths\":[\"$FILEPATH\"],\"saveTo\":\"$DEMO/raw\"}" >/dev/null 2>&1
  local LOCAL=$(basename "$FILEPATH")
  if [[ -f "$DEMO/raw/$LOCAL" ]]; then
    cp "$DEMO/raw/$LOCAL" "$DEMO/clips/$id.webm"
    echo "    saved -> $DEMO/clips/$id.webm ($(du -h "$DEMO/clips/$id.webm" | cut -f1))"
  else
    echo "    ERROR: pull failed for $LOCAL"
  fi
}

# === Scene 1: hero — populated dashboard ===
scene_hero() {
  # Just slow scroll the cards for the hero
  for i in 0 100 200 300 200 100 0; do
    eval_pup "window.scrollTo({top:$i, behavior:'smooth'})"
    sleep 1.5
  done
}

# === Scene 2: library — card detail ===
scene_library() {
  # Hover/highlight individual cards briefly
  eval_pup "(()=>{var c=Array.from(document.querySelectorAll('.card')).slice(0,4); var i=0; var iv=setInterval(()=>{c.forEach(x=>x.style.outline=''); if(i<c.length){c[i].style.outline='2px solid #3b82f6'; c[i].scrollIntoView({block:'center'});} i++; if(i>c.length){clearInterval(iv);}},1500); window._sceneLib=iv;})()"
  sleep 8
  eval_pup "clearInterval(window._sceneLib); document.querySelectorAll('.card').forEach(c=>c.style.outline='')"
}

# === Scene 3: credentials — masked + click-to-reveal ===
scene_credentials() {
  eval_pup "document.getElementById('btn-creds').click()"
  sleep 3
  # Click a pw-mask to reveal
  eval_pup "(()=>{var pw=document.querySelectorAll('.pw-mask'); if(pw[1]) pw[1].click();})()"
  sleep 3
  # Hide it again
  eval_pup "(()=>{var pw=document.querySelectorAll('.pw-mask'); if(pw[1]) pw[1].click();})()"
  sleep 2
}

# === Scene 4: detail panel — BME688 ===
scene_detail() {
  # Close cred popover
  eval_pup "(()=>{var b=document.getElementById('cred-close'); if(b) b.click();})()"
  sleep 2
  # Click BME688 card
  eval_pup "(()=>{var c=Array.from(document.querySelectorAll('.card')).find(c=>/BME688/.test(c.textContent)); if(c){c.scrollIntoView({block:'center', behavior:'smooth'}); setTimeout(()=>c.click(),500);}})()"
  sleep 8
}

# === Scene 5: UL Pro fast-path — mock activity ===
scene_ul_pro() {
  # Cycle through realistic stages so the dashboard heartbeat shows the flow
  local STAGES=("searching UL Pro" "loading part page" "selecting Altium + Fusion formats" "submitting download request" "downloading from UL Pro" "pulling zip into chip-fetcher" "distributing Altium + Fusion" "done")
  for s in "${STAGES[@]}"; do
    post_act "BQ25798RQMR" "$s"
    sleep 1.4
  done
  curl -s -X POST http://127.0.0.1:8780/api/activity -H "Content-Type: application/json" -d '{}' > /dev/null
  sleep 1
}

# Drive
echo "=== chip-fetcher 0.1.3 demo recording ==="
record_scene hero 12 scene_hero
record_scene library 10 scene_library
record_scene credentials 12 scene_credentials
record_scene detail 12 scene_detail
record_scene ul_pro 14 scene_ul_pro
echo "=== done ==="
ls -la $DEMO/clips/
