#!/bin/bash
# NodeSeek 签到 - VP404 (Chrome CDP)
CDP="http://127.0.0.1:18800"
LOG="$HOME/.openclaw/workspace/scripts/checkin.log"
SESSION="0f20d87bfa1e3ddbe44b3f0eff84359a"
PATH="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin"

# 确保 Chrome CDP 在跑
if ! curl -s "$CDP/json/version" >/dev/null 2>&1; then
  /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome \
    --remote-debugging-port=18800 --user-data-dir=/tmp/chrome-debug-profile &>/dev/null &
  sleep 5
fi

TAB_WS=$(curl -s "$CDP/json/list" | node -e "let d='';process.stdin.on('data',c=>d+=c);process.stdin.on('end',()=>{const t=JSON.parse(d).find(t=>t.type==='page');console.log(t?.webSocketDebuggerUrl||'')})")
[ -z "$TAB_WS" ] && echo "$(date '+%Y-%m-%d %H:%M') VP404: no tab" >> "$LOG" && exit 1

RESULT=$(cd /tmp && node -e "
const c=new(require('ws'))('$TAB_WS');
c.on('open',()=>c.send(JSON.stringify({id:1,method:'Network.setCookie',params:{name:'session',value:'$SESSION',domain:'www.nodeseek.com',path:'/',secure:true}})));
let s=0;c.on('message',m=>{s++;
if(s===1)c.send(JSON.stringify({id:2,method:'Page.navigate',params:{url:'https://www.nodeseek.com'}}));
else if(s===2)setTimeout(()=>c.send(JSON.stringify({id:3,method:'Runtime.evaluate',params:{expression:\"fetch('/api/attendance',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({random:true})}).then(r=>r.json()).then(d=>JSON.stringify(d))\",awaitPromise:true}})),3000);
else{const r=JSON.parse(m.toString());console.log(r.result?.result?.value||'error');c.close();}});
setTimeout(()=>process.exit(1),15000);
" 2>&1)

echo "$(date '+%Y-%m-%d %H:%M') VP404: $RESULT" >> "$LOG"
