#!/usr/bin/env node
const WebSocket = require('ws');
const fs = require('fs');
const path = require('path');

const CDP_URL = 'ws://127.0.0.1:18800/devtools/browser/61ae08b1-1fab-420a-a3df-c5635446065e';
const COOKIE = '_nk=dc4d1551406351a93c09082ea08e2d2e';
const TARGET_URL = 'https://www.nodeseek.com';
const LOG_FILE = path.join(__dirname, 'checkin.log');

let ws;
let sessionId;
let targetId;
let messageId = 1;

function log(msg) {
  const timestamp = new Date().toISOString();
  const logMsg = `[${timestamp}] ${msg}\n`;
  console.log(logMsg.trim());
  fs.appendFileSync(LOG_FILE, logMsg);
}

function send(method, params = {}) {
  const id = messageId++;
  const message = JSON.stringify({ id, method, params, sessionId });
  ws.send(message);
  return id;
}

function waitForMessage(id) {
  return new Promise((resolve) => {
    const handler = (data) => {
      const msg = JSON.parse(data);
      if (msg.id === id) {
        ws.removeListener('message', handler);
        resolve(msg);
      }
    };
    ws.on('message', handler);
  });
}

async function main() {
  try {
    log('开始 NodeSeek 朦胧签到');

    // Connect to CDP
    ws = new WebSocket(CDP_URL);
    
    await new Promise((resolve, reject) => {
      ws.on('open', resolve);
      ws.on('error', reject);
    });

    log('已连接到 Chrome CDP');

    // Create new tab
    const createId = send('Target.createTarget', { url: 'about:blank' });
    const createResp = await waitForMessage(createId);
    targetId = createResp.result.targetId;
    log(`创建标签页: ${targetId}`);

    // Attach to target
    const attachId = send('Target.attachToTarget', { targetId, flatten: true });
    const attachResp = await waitForMessage(attachId);
    sessionId = attachResp.result.sessionId;
    log(`附加到会话: ${sessionId}`);

    // Enable necessary domains
    send('Network.enable');
    send('Page.enable');
    send('Runtime.enable');

    // Set cookie
    const cookieId = send('Network.setCookie', {
      name: '_nk',
      value: 'dc4d1551406351a93c09082ea08e2d2e',
      domain: '.nodeseek.com',
      path: '/',
      secure: true,
      httpOnly: true,
      sameSite: 'Lax'
    });
    await waitForMessage(cookieId);
    log('已设置 cookie');

    // Navigate to NodeSeek
    const navId = send('Page.navigate', { url: TARGET_URL });
    await waitForMessage(navId);
    log(`导航到 ${TARGET_URL}`);

    // Wait for page load
    await new Promise((resolve) => {
      const handler = (data) => {
        const msg = JSON.parse(data);
        if (msg.method === 'Page.loadEventFired') {
          ws.removeListener('message', handler);
          resolve();
        }
      };
      ws.on('message', handler);
    });
    log('页面加载完成');

    // Wait 8 seconds
    await new Promise(resolve => setTimeout(resolve, 8000));
    log('等待 8 秒后执行签到');

    // Execute check-in
    const evalId = send('Runtime.evaluate', {
      expression: `
        fetch('/api/attendance', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ random: true })
        })
        .then(async r => {
          const text = await r.text();
          try {
            return JSON.stringify(JSON.parse(text));
          } catch {
            return JSON.stringify({ status: r.status, body: text.substring(0, 200) });
          }
        })
        .catch(e => JSON.stringify({ error: e.message }))
      `,
      awaitPromise: true,
      returnByValue: true
    });
    const evalResp = await waitForMessage(evalId);
    
    if (evalResp.result && evalResp.result.result) {
      const result = evalResp.result.result.value;
      log(`签到结果: ${result}`);
    } else {
      log(`签到失败: ${JSON.stringify(evalResp)}`);
    }

    // Close tab
    const closeId = send('Target.closeTarget', { targetId });
    await waitForMessage(closeId);
    log('已关闭标签页');

    ws.close();
    log('NodeSeek 朦胧签到完成');

  } catch (error) {
    log(`签到出错: ${error.message}`);
    if (ws && ws.readyState === WebSocket.OPEN) {
      if (targetId) {
        send('Target.closeTarget', { targetId });
      }
      ws.close();
    }
    process.exit(1);
  }
}

main();
