/**
 * SG_SS Cookie Solver
 * 从 Google JS 壳页面中提取并执行 SG_SS 生成脚本
 * 用法: node lens_sgss_solver.js <html_file>
 * 输出: SG_SS cookie 值到 stdout
 */
const fs = require('fs');
const { JSDOM } = require('jsdom');

const htmlFile = process.argv[2];
if (!htmlFile) { process.exit(1); }

const html = fs.readFileSync(htmlFile, 'utf-8');

const dom = new JSDOM(html, {
  url: 'https://www.google.com/search',
  runScripts: 'dangerously',
  pretendToBeVisual: true,
  beforeParse(window) {
    // Polyfill navigator
    Object.defineProperty(window.navigator, 'userAgent', {
      value: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/147.0.0.0',
      configurable: true
    });

    // Intercept document.cookie to capture SG_SS
    let cookies = '';
    const origCookieDesc = Object.getOwnPropertyDescriptor(window.Document.prototype, 'cookie') ||
                           Object.getOwnPropertyDescriptor(window.HTMLDocument.prototype, 'cookie');

    Object.defineProperty(window.document, 'cookie', {
      get() { return cookies; },
      set(val) {
        cookies = val;
        if (val.startsWith('SG_SS=')) {
          const sgss = val.split(';')[0].replace('SG_SS=', '');
          process.stdout.write(sgss);
          setTimeout(() => process.exit(0), 10);
        }
      },
      configurable: true
    });

    // Stub functions the script calls after setting cookie
    window.N = window.N || function() {};
    window.O = window.O || function() {};
    window.T = window.T || function() {};
    window.U = window.U || function() {};
    window.S = window.S || function() { return ''; };
  }
});

// Timeout fallback
setTimeout(() => {
  // Try to extract SG_SS from any cookie that was set
  const cookies = dom.window.document.cookie || '';
  const m = cookies.match(/SG_SS=([^;]+)/);
  if (m) {
    process.stdout.write(m[1]);
  }
  process.exit(0);
}, 5000);
