#!/usr/bin/env tsx
/**
 * 检查小红书账号 Cookie 有效性
 */
import { initDatabase } from '../models/index.js';
import { PlatformAccount } from '../models/entities/PlatformAccount.js';
import { AppDataSource } from '../models/index.js';
import { CookieManager } from '../automation/cookie.js';
import { logger } from '../utils/logger.js';
import { chromium } from 'playwright';

async function main() {
  logger.info('========================================');
  logger.info('检查小红书账号 Cookie 有效性');
  logger.info('========================================');

  await initDatabase();
  logger.info('数据库连接已初始化');

  const accountId = parseInt(process.argv[2] || '35');
  
  const accountRepository = AppDataSource.getRepository(PlatformAccount);
  const account = await accountRepository.findOne({
    where: {
      platform: 'xiaohongshu',
      id: accountId,
    },
  });

  if (!account) {
    logger.error(`未找到账号 ID: ${accountId}`);
    process.exit(1);
  }

  logger.info(`找到账号: ID=${account.id}, 名称=${account.accountName}`);

  if (!account.cookieData) {
    logger.error('账号没有 Cookie 数据');
    process.exit(1);
  }

  // 解密 Cookie
  let decryptedCookies: string;
  try {
    decryptedCookies = CookieManager.decrypt(account.cookieData);
    logger.info('✓ Cookie 解密成功');
  } catch {
    decryptedCookies = account.cookieData;
    logger.info('✓ 使用原始 Cookie 数据');
  }

  // 解析 Cookie
  let cookieList: { name: string; value: string; domain: string; path: string }[];
  try {
    cookieList = JSON.parse(decryptedCookies);
    logger.info(`✓ 解析到 ${cookieList.length} 个 Cookie (JSON 格式)`);
  } catch {
    // 字符串格式
    cookieList = decryptedCookies.split(';').map(item => {
      const [name, value] = item.trim().split('=');
      return { name: name.trim(), value: (value || '').trim(), domain: '.xiaohongshu.com', path: '/' };
    }).filter(c => c.name && c.value);
    logger.info(`✓ 解析到 ${cookieList.length} 个 Cookie (字符串格式)`);
  }

  if (cookieList.length === 0) {
    logger.error('❌ Cookie 列表为空');
    process.exit(1);
  }

  // 检查关键 Cookie
  const keyCookies = ['web_session', 'a1', 'webId', 'websectiga'];
  const foundKeyCookies = cookieList.filter(c => keyCookies.includes(c.name));
  logger.info(`关键 Cookie: ${foundKeyCookies.map(c => c.name).join(', ') || '未找到'}`);

  // 使用 Playwright 检查 Cookie 有效性
  logger.info('\n========================================');
  logger.info('使用浏览器检查 Cookie 有效性...');
  logger.info('========================================\n');

  const browser = await chromium.launch({ headless: true });
  const context = await browser.newContext({
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
  });

  try {
    const page = await context.newPage();

    // 设置 Cookie
    await context.addCookies(cookieList.map(c => ({
      name: c.name,
      value: c.value,
      domain: c.domain || '.xiaohongshu.com',
      path: c.path || '/',
    })));

    logger.info('✓ Cookie 已设置到浏览器');

    // 访问创作者中心首页
    logger.info('正在访问创作者中心首页...');
    try {
      await page.goto('https://creator.xiaohongshu.com/', {
        waitUntil: 'domcontentloaded',
        timeout: 30000,
      });
      logger.info('✓ 页面加载成功');
    } catch (error) {
      logger.warn(`⚠️ 页面加载超时: ${error}`);
    }

    // 检查当前 URL
    const currentUrl = await page.url();
    logger.info(`当前页面 URL: ${currentUrl}`);

    if (currentUrl.includes('login') || currentUrl.includes('passport')) {
      logger.error('❌ Cookie 已失效！页面跳转到了登录页');
      logger.error(`登录页 URL: ${currentUrl}`);
      process.exit(1);
    }

    // 检查页面标题
    const title = await page.title();
    logger.info(`页面标题: ${title}`);

    // 尝试访问笔记管理页面
    logger.info('\n正在访问笔记管理页面...');
    try {
      await page.goto('https://creator.xiaohongshu.com/new/note-manager', {
        waitUntil: 'domcontentloaded',
        timeout: 30000,
      });
      
      await page.waitForTimeout(1000); // 等待页面稳定
      const noteManagerUrl = typeof page.url === 'function' ? await page.url() : String(page.url || '');
      logger.info(`笔记管理页面 URL: ${noteManagerUrl}`);

      if (typeof noteManagerUrl === 'string' && (noteManagerUrl.includes('login') || noteManagerUrl.includes('passport'))) {
        logger.error('❌ Cookie 已失效！笔记管理页面跳转到了登录页');
        process.exit(1);
      }

      logger.info('✓ 笔记管理页面访问成功');

      // 尝试调用 API 获取作品列表
      logger.info('\n正在测试 API 调用...');
      const apiResult = await page.evaluate(async () => {
        try {
          const url = 'https://edith.xiaohongshu.com/web_api/sns/v5/creator/note/user/posted?tab=0&page=0';
          const headers: Record<string, string> = { 'Accept': 'application/json' };
          
          // 尝试获取签名
          if (typeof window !== 'undefined' && typeof (window as any)._webmsxyw === 'function') {
            try {
              const sign = (window as any)._webmsxyw(url, '');
              headers['x-s'] = sign['X-s'];
              headers['x-t'] = String(sign['X-t']);
            } catch (e) {
              // 忽略签名错误
            }
          }

          const res = await fetch(url, {
            method: 'GET',
            credentials: 'include',
            headers,
          });
          
          const data = await res.json();
          return {
            success: res.ok,
            status: res.status,
            hasData: !!data.data,
            notesCount: data.data?.notes?.length || 0,
            code: data.code,
            message: data.msg || data.message || '',
          };
        } catch (e) {
          return {
            success: false,
            error: String(e),
          };
        }
      });

      logger.info(`API 调用结果:`);
      logger.info(`  成功: ${apiResult.success}`);
      logger.info(`  状态码: ${apiResult.status || 'N/A'}`);
      logger.info(`  有数据: ${apiResult.hasData || false}`);
      logger.info(`  作品数: ${apiResult.notesCount || 0}`);
      logger.info(`  代码: ${apiResult.code || 'N/A'}`);
      if (apiResult.message) {
        logger.info(`  消息: ${apiResult.message}`);
      }
      if (apiResult.error) {
        logger.error(`  错误: ${apiResult.error}`);
      }

      if (apiResult.success && apiResult.hasData) {
        logger.info('\n✅ Cookie 有效！可以正常获取作品数据');
      } else if (apiResult.success && !apiResult.hasData) {
        logger.warn('\n⚠️ Cookie 可能有效，但 API 返回空数据');
        logger.warn('可能原因: 账号没有作品，或 API 调用失败');
      } else {
        logger.error('\n❌ Cookie 可能失效，API 调用失败');
      }

    } catch (error) {
      logger.error(`访问笔记管理页面失败: ${error}`);
      if (error instanceof Error) {
        logger.error(`错误堆栈: ${error.stack}`);
      }
    }

    await browser.close();
  } catch (error) {
    logger.error(`检查 Cookie 时发生错误: ${error}`);
    if (error instanceof Error) {
      logger.error(`错误堆栈: ${error.stack}`);
    }
    await browser.close();
    process.exit(1);
  }

  process.exit(0);
}

main();
