import puppeteer from 'puppeteer-core';
import fs from 'fs';

const browserURL = 'http://127.0.0.1:18800';
const cookie = {
  name: '_nk',
  value: '3cfeb30b562daec31ba63bf64fdb3838',
  domain: '.nodeseek.com',
  path: '/',
  httpOnly: false,
  secure: true
};

let browser, page;

try {
  browser = await puppeteer.connect({ browserURL, defaultViewport: null });
  page = await browser.newPage();
  
  await page.setCookie(cookie);
  await page.goto('https://www.nodeseek.com', { waitUntil: 'networkidle2', timeout: 30000 });
  
  const response = await page.evaluate(async () => {
    const res = await fetch('/api/attendance?random=1', { method: 'POST' });
    return { status: res.status, data: await res.json() };
  });
  
  const timestamp = new Date().toISOString();
  const logEntry = `[${timestamp}] VP404签到: ${JSON.stringify(response)}\n`;
  
  fs.appendFileSync('scripts/checkin.log', logEntry);
  
  await page.close();
  console.log('✅ 签到成功:', response.data);
  
} catch (err) {
  const timestamp = new Date().toISOString();
  const logEntry = `[${timestamp}] VP404签到失败: ${err.message}\n`;
  fs.appendFileSync('scripts/checkin.log', logEntry);
  console.error('❌ 签到失败:', err.message);
  if (page) await page.close().catch(() => {});
  process.exit(1);
}
