import fs from 'fs';
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const WebSocket = require('ws');

const LOG = '/Users/jianzhang/.openclaw/workspace/scripts/checkin.log';
const ts = new Date().toISOString();

(async () => {
  try {
    const verRes = await fetch('http://127.0.0.1:18800/json/version');
    const ver = await verRes.json();
    const wsUrl = ver.webSocketDebuggerUrl;
    if (!wsUrl) throw new Error('No webSocketDebuggerUrl');

    const ws = new WebSocket(wsUrl);
    let id = 1;
    const pending = new Map();
    ws.on('message', d => {
      const m = JSON.parse(d);
      if (m.id && pending.has(m.id)) { pending.get(m.id)(m); pending.delete(m.id); }
    });
    const send = (method, params = {}) => new Promise(r => {
      const i = id++;
      pending.set(i, r);
      ws.send(JSON.stringify({ id: i, method, params }));
    });
    await new Promise(r => ws.on('open', r));

    // Create new tab
    const target = await send('Target.createTarget', { url: 'about:blank' });
    const targetId = target.result.targetId;

    // Attach
    const sess = await send('Target.attachToTarget', { targetId, flatten: true });
    const sessionId = sess.result.sessionId;

    const sendS = (method, params = {}) => new Promise(r => {
      const i = id++;
      pending.set(i, r);
      ws.send(JSON.stringify({ id: i, method, params, sessionId }));
    });

    await sendS('Network.enable');
    await sendS('Page.enable');

    // Set cookie
    await sendS('Network.setCookie', {
      name: '_nk',
      value: 'dc4d1551406351a93c09082ea08e2d2e',
      domain: '.nodeseek.com',
      path: '/',
      httpOnly: true,
      secure: true
    });

    // Navigate
    await sendS('Page.navigate', { url: 'https://www.nodeseek.com' });

    // Wait for page load
    await new Promise(r => {
      const handler = d => {
        const m = JSON.parse(d);
        if (m.method === 'Page.loadEventFired') { ws.removeListener('message', handler); r(); }
      };
      ws.on('message', handler);
    });

    // Wait 8s
    await new Promise(r => setTimeout(r, 8000));

    // Call attendance API
    await sendS('Runtime.enable');
    const result = await sendS('Runtime.evaluate', {
      expression: `(async () => {
        const res = await fetch('/api/attendance', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ random: true })
        });
        return await res.text();
      })()`,
      awaitPromise: true,
      returnByValue: true
    });

    const val = result.result?.result?.value || JSON.stringify(result.result);
    const logMsg = `[${ts}] NodeSeek 签到: ${val}\n`;
    fs.appendFileSync(LOG, logMsg);
    console.log('签到结果:', val);

    // Close tab
    await send('Target.closeTarget', { targetId });
    ws.close();

  } catch (e) {
    const logMsg = `[${ts}] 签到失败: ${e.message}\n`;
    fs.appendFileSync(LOG, logMsg);
    console.error('失败:', e.message);
  }
})();
