import WebSocket from 'ws';
import { appendFileSync } from 'fs';

const CDP_BASE = 'http://127.0.0.1:18800';
const COOKIE = 'dc4d1551406351a93c09082ea08e2d2e';
const TARGET_URL = 'https://www.nodeseek.com';
const LOG_FILE = process.env.HOME + '/.openclaw/workspace/scripts/checkin.log';

let ws;
let msgId = 0;
let pending = new Map();
let targetId;
let sessionId;

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

async function getBrowserWsUrl() {
  const resp = await fetch(`${CDP_BASE}/json/version`);
  const data = await resp.json();
  return data.webSocketDebuggerUrl;
}

function send(method, params = {}) {
  return new Promise((resolve, reject) => {
    const id = ++msgId;
    const msg = { id, method, params };
    if (sessionId) msg.sessionId = sessionId;
    
    pending.set(id, { resolve, reject });
    ws.send(JSON.stringify(msg));
    
    // 10秒超时
    setTimeout(() => {
      if (pending.has(id)) {
        pending.delete(id);
        reject(new Error(`Timeout waiting for ${method}`));
      }
    }, 10000);
  });
}

async function main() {
  try {
    log('开始 NodeSeek 朦胧账号签到...');
    
    // 获取 CDP WebSocket URL
    const wsUrl = await getBrowserWsUrl();
    log(`CDP URL: ${wsUrl}`);
    
    // 连接 CDP
    ws = new WebSocket(wsUrl);
    
    // 处理所有消息
    ws.on('message', (data) => {
      const msg = JSON.parse(data);
      
      // 处理命令响应
      if (msg.id !== undefined && pending.has(msg.id)) {
        const { resolve, reject } = pending.get(msg.id);
        pending.delete(msg.id);
        if (msg.error) reject(msg.error);
        else resolve(msg.result);
      }
    });
    
    await new Promise((resolve, reject) => {
      ws.on('open', resolve);
      ws.on('error', reject);
    });
    log('CDP 连接成功');

    // 创建新标签页
    const target = await send('Target.createTarget', { url: 'about:blank' });
    targetId = target.targetId;
    log(`创建标签页: ${targetId}`);

    // 附着到标签页
    const session = await send('Target.attachToTarget', { targetId, flatten: true });
    sessionId = session.sessionId;
    log(`附着到会话: ${sessionId}`);

    // 启用必要域
    await send('Page.enable');
    await send('Runtime.enable');
    await send('Network.enable');
    log('启用域成功');

    // 设置 cookie
    await send('Network.setCookie', {
      name: '_nk',
      value: COOKIE,
      domain: '.nodeseek.com',
      path: '/'
    });
    log('Cookie 设置成功');

    // 设置页面加载监听
    const loadPromise = new Promise(resolve => {
      ws.on('message', (data) => {
        const msg = JSON.parse(data);
        if (msg.method === 'Page.loadEventFired') {
          resolve();
        }
      });
    });
    
    // 导航
    await send('Page.navigate', { url: TARGET_URL });
    log(`导航到 ${TARGET_URL}`);
    
    await loadPromise;
    log('页面加载完成');

    // 等待 8 秒
    await new Promise(r => setTimeout(r, 8000));
    log('等待 8 秒完成');

    // 执行签到
    const result = await send('Runtime.evaluate', {
      expression: `fetch('/api/attendance',{
        method:'POST',
        headers:{'Content-Type':'application/json'},
        body:JSON.stringify({random:true})
      }).then(r=>r.json()).catch(e=>({error:e.message}))`,
      returnByValue: true,
      awaitPromise: true
    });
    
    const signResult = result.result?.value;
    log(`签到结果: ${JSON.stringify(signResult)}`);

    // 关闭标签页
    await send('Target.closeTarget', { targetId });
    log('标签页已关闭');

    ws.close();
    log('签到完成');
    
    return signResult;
  } catch (err) {
    log(`错误: ${err.message}`);
    if (ws) ws.close();
    throw err;
  }
}

main().catch(() => process.exit(1));
