#!/bin/bash
# Drive a chip's manufacturer page → Ultra Librarian deep-link → set form (STEP, KiCAD v6+, mm, T&C).
#
# Usage: cf-drive.sh <MPN> [vendor]
#   vendor (optional): ti | st | adi | nxp | microchip | renesas
#                      Default: ti.
#
# After this returns, run cf-autowatch.sh <MPN> & to auto-pull the download.

set -u
MPN="${1:?usage: cf-drive.sh <MPN> [vendor]}"
VENDOR="${2:-ti}"
echo "=== driving $MPN (vendor: $VENDOR) ==="

case "$VENDOR" in
  ti)         PROD_URL="https://www.ti.com/product/$MPN" ;;
  st)         PROD_URL="https://www.st.com/en/imaging-and-photonics-solutions/${MPN,,}.html" ;;  # ST URL varies by category
  adi)        PROD_URL="https://www.analog.com/en/products/${MPN,,}.html" ;;
  nxp)        PROD_URL="https://www.nxp.com/products/$MPN" ;;
  microchip)  PROD_URL="https://www.microchip.com/en-us/product/$MPN" ;;
  renesas)    PROD_URL="https://www.renesas.com/us/en/products/$MPN" ;;
  *) echo "FAIL: unknown vendor $VENDOR (try: ti st adi nxp microchip renesas)"; exit 1 ;;
esac

adom-desktop browser_navigate "{\"sessionId\":\"chip-fetcher\",\"url\":\"$PROD_URL\"}" >/dev/null
sleep 6

# Find any "Ultra Librarian" link on the page (vendors all use the same vendor.ultralibrarian.com pattern,
# but the path is per-vendor: /TI/, /stmicro/, /adi/, etc.).
UL_URL=$(adom-desktop browser_eval '{"sessionId":"chip-fetcher","expr":"(() => { const a = Array.from(document.querySelectorAll(\"a\")).find(x => x.href && /ultralibrarian\\.com\\/.*\\/embedded/i.test(x.href)); return a ? a.href : \"NONE\"; })()"}' 2>/dev/null \
  | python3 -c "import sys,json; print(json.load(sys.stdin)['result'])" 2>/dev/null)

if [ "$UL_URL" = "NONE" ] || [ -z "$UL_URL" ]; then
  echo "FAIL: no UL link on $VENDOR page for $MPN ($PROD_URL)"
  exit 1
fi
echo "UL link: $UL_URL"

adom-desktop browser_navigate "{\"sessionId\":\"chip-fetcher\",\"url\":\"$UL_URL\"}" >/dev/null
sleep 6
adom-desktop browser_eval '{"sessionId":"chip-fetcher","expr":"(() => { const choose = Array.from(document.querySelectorAll(\"a, button\")).find(b => /choose.*cad/i.test(b.textContent)); if (choose) choose.click(); })()"}' >/dev/null
sleep 3

# Set the form using LABEL-based selection (not ID). TI uses MfrThreeDModel, ADI uses ThreeDModel,
# others may use other IDs — but the visible label "STEP" / "KiCAD v6+" is consistent across vendors.
adom-desktop browser_eval '{"sessionId":"chip-fetcher","expr":"(() => { const cbs = Array.from(document.querySelectorAll(\"input[type=checkbox]\")); const byLabel = re => cbs.find(c => re.test((c.parentElement?.textContent || \"\").trim().split(\"\\n\")[0])); const step = byLabel(/^STEP$/i); const kicad = byLabel(/^KiCAD v6\\+/i) || byLabel(/^KiCAD v6$/i); const tc = byLabel(/agree.*Terms|Terms.*Conditions/i); if (step && !step.checked) step.click(); if (kicad && !kicad.checked) kicad.click(); if (tc && !tc.checked) tc.click(); const sels = Array.from(document.querySelectorAll(\"select\")).filter(s => Array.from(s.options).some(o => /mm|metric/i.test(o.textContent))); for (const s of sels) { const m = Array.from(s.options).find(o => /metric|mm/i.test(o.textContent)); if (m) { s.value = m.value; s.dispatchEvent(new Event(\"change\",{bubbles:true})); } } return JSON.stringify({step: step?.checked, kicad: kicad?.checked, tc: tc?.checked, units: sels[0]?.value}); })()"}' 2>&1 | head -5

adom-desktop browser_raise_os_window '{"sessionId":"chip-fetcher"}' >/dev/null
echo "form ready — click CAPTCHA on pup window"
