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

const CDP_URL = process.argv[2];
const COOKIE_VALUE = "dc4d1551406351a93c09082ea08e2d2e";
const TARGET_URL = "https://www.nodeseek.com";
const LOG_FILE = process.env.HOME + "/.openclaw/workspace/scripts/checkin.log";

async function sleep(ms) {
  return new Promise(r => setTimeout(r, ms));
}

let msgId = 1;
function send(ws, method, params = {}, sessionId) {
  return new Promise((resolve, reject) => {
    const id = msgId++;
    const payload = { id, method, params };
    if (sessionId) payload.sessionId = sessionId;
    ws.send(JSON.stringify(payload));
    const handler = (data) => {
      try {
        const msg = JSON.parse(data);
        if (msg.id === id) {
          ws.removeListener("message", handler);
          if (msg.error) reject(msg.error);
          else resolve(msg.result);
        }
      } catch(e) {}
    };
    ws.on("message", handler);
  });
}

async function main() {
  const ws = new WebSocket(CDP_URL);
  
  await new Promise((resolve, reject) => {
    ws.on("open", resolve);
    ws.on("error", reject);
  });

  console.log("Connected to CDP");

  // 创建新标签页
  const { targetId } = await send(ws, "Target.createTarget", {
    url: "about:blank"
  });
  console.log("Created target:", targetId);

  // 连接到新标签页
  const { sessionId } = await send(ws, "Target.attachToTarget", {
    targetId,
    flatten: true
  });
  console.log("Attached to target, sessionId:", sessionId);

  // 设置 cookie
  await send(ws, "Network.setCookie", {
    name: "_nk",
    value: COOKIE_VALUE,
    domain: ".nodeseek.com",
    path: "/"
  }, sessionId);
  console.log("Cookie set");

  // 启用 Page 域
  await send(ws, "Page.enable", {}, sessionId);

  // 导航到页面并等待加载
  const loadPromise = new Promise((resolve) => {
    const handler = (data) => {
      try {
        const msg = JSON.parse(data);
        if (msg.method === "Page.loadEventFired") {
          ws.removeListener("message", handler);
          resolve();
        }
      } catch(e) {}
    };
    ws.on("message", handler);
  });

  await send(ws, "Page.navigate", { url: TARGET_URL }, sessionId);
  console.log("Navigating to:", TARGET_URL);
  
  await loadPromise;
  console.log("Page loaded, waiting 8 seconds...");

  await sleep(8000);

  // 执行签到
  const result = await send(ws, "Runtime.evaluate", {
    expression: `fetch("/api/attendance", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ random: true })
    }).then(r => r.json())`,
    returnByValue: true,
    awaitPromise: true
  }, sessionId);

  console.log("Check-in result:", JSON.stringify(result.result?.value || result));

  // 记录日志
  const logEntry = `[${new Date().toISOString()}] NodeSeek 朦胧签到: ${JSON.stringify(result.result?.value || result)}\n`;
  fs.appendFileSync(LOG_FILE, logEntry);
  console.log("Logged to:", LOG_FILE);

  // 关闭标签页
  await send(ws, "Target.closeTarget", { targetId });
  console.log("Target closed");

  ws.close();
  console.log("Done");

  return result.result?.value || result;
}

main().catch(err => {
  console.error("Error:", err);
  process.exit(1);
});
