#!/usr/bin/env node
import puppeteer from 'puppeteer-core';
import { appendFileSync } from 'fs';

const LOG = '/Users/jianzhang/.openclaw/workspace/scripts/checkin.log';

function log(msg) {
  const ts = new Date().toISOString();
  appendFileSync(LOG, `[${ts}] ${msg}\n`);
  console.log(msg);
}

async function run() {
  const browser = await puppeteer.connect({
    browserURL: 'http://127.0.0.1:18800'
  });

  const pages = await browser.pages();
  let page = pages.find(p => p.url().includes('nodeseek.com'));
  
  if (!page) {
    page = await browser.newPage();
    await page.goto('https://www.nodeseek.com');
    log('创建新标签页');
  } else {
    log('使用已有标签页');
  }

  await new Promise(r => setTimeout(r, 3000));

  const result = await page.evaluate(async () => {
    const res = await fetch('/api/attendance', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ random: true })
    });
    return res.json();
  });

  log(`签到结果: ${JSON.stringify(result)}`);

  await browser.disconnect();
}

run().catch((e) => {
  log(`错误: ${e.message}`);
  process.exit(1);
});
