/**
 * 抖音发布可行性测试
 * 
 * 测试内容：
 * 1. 验证 Cookie 是否有效
 * 2. 获取用户信息
 * 3. 尝试访问视频上传接口
 */

const axios = require('axios');

// 从你提供的 curl 命令中提取的 Cookie
const TEST_COOKIE = 'x-web-secsdk-uid=dad3a1e2-8a04-479e-b2f7-23e5fb2d3886; gfkadpd=2906,33638; _tea_utm_cache_2906=undefined; csrf_session_id=62637711d69c21ff4bf1659c19031660; bd_ticket_guard_client_web_domain=2; passport_csrf_token=7192948c206b4372d66f598cea1d7c61; passport_csrf_token_default=7192948c206b4372d66f598cea1d7c61; biz_trace_id=373e3792; s_v_web_id=verify_mob7d51c_x0sF5nei_Cco9_4BUu_98sZ_aFkNzoENvP5B; passport_mfa_token=CjflZ3s7mnwLbkofuNtTzy2RsWexDVR6K%2BsIK5%2F25wtrZUHKKJlKLB0odxhfRTaTZZzqnjn%2BRfzNGkoKPAAAAAAAAAAAAABQVsh9LUcYeGk2iu325F3Bec5Pp5ESQKauA5qdZBsXdV7z3GHwkN6zD%2FJMviqOn2GmJxDvyo8OGPax0WwgAiIBAy3dXEI%3D; d_ticket=155055d9db38f2263ee71e2fc00d49f77a031; passport_assist_user=CkF5DKWV1qhlmpMHAtyVnDRmURdZiRjWmCWTEfn4TuROQNv4kdp7TSS47uow1Dmp1gPZyHMpfPkDyhAMMMpTQHiOBBpKCjwAAAAAAAAAAAAAUFbsnhX8yQaNnoGrvUaWJnu6yz67aJ1Utu-MPkDIrHOKT5VI7dMZsDd0j5hnJePaJlUQ78qPDhiJr9ZUIAEiAQMHOYLY; n_mh=NZ66y_3jbT04s2gefO-EMKEB6EsWtjVtv18mMDhVYNc; passport_auth_status=fdb4f4d164ad11b102e78f3885a24dec%2C; passport_auth_status_ss=fdb4f4d164ad11b102e78f3885a24dec%2C; sid_guard=e4f165b3ec9c0c2dd1cf045e27f416e1%7C1776931919%7C5184000%7CMon%2C+22-Jun-2026+08%3A11%3A59+GMT; uid_tt=2bab11562b398876659ba823f98b1f3e; uid_tt_ss=2bab11562b398876659ba823f98b1f3e; sid_tt=e4f165b3ec9c0c2dd1cf045e27f416e1; sessionid=e4f165b3ec9c0c2dd1cf045e27f416e1; sessionid_ss=e4f165b3ec9c0c2dd1cf045e27f416e1; session_tlb_tag=sttt%7C9%7C5PFls-ycDC3RzwReJ_QW4f_________hTYyTymF9qfwYeiMCWpKD1Eb7EiLJtnpA63x9e2YieXo%3D; is_staff_user=false; has_biz_token=false; sid_ucp_v1=1.0.0-KGM0MzY5MjE2ZDQwZDA3NGI1YTQ1MzUxNWRlOWE4MmMwZWQ5Y2QyNTYKIQi-z9Dv0PT1BRDPqKfPBhjaFiAMMObBw_IFOAJA8QdIBBoCbGYiIGU0ZjE2NWIzZWM5YzBjMmRkMWNmMDQ1ZTI3ZjQxNmUx; ssid_ucp_v1=1.0.0-KGM0MzY5MjE2ZDQwZDA3NGI1YTQ1MzUxNWRlOWE4MmMwZWQ5Y2QyNTYKIQi-z9Dv0PT1BRDPqKfPBhjaFiAMMObBw_IFOAJA8QdIBBoCbGYiIGU0ZjE2NWIzZWM5YzBjMmRkMWNmMDQ1ZTI3ZjQxNmUx; _bd_ticket_crypt_doamin=2; _bd_ticket_crypt_cookie=c6e1b35622e0600393a280031b3357a6; __security_mc_1_s_sdk_sign_data_key_web_protect=309e8ad3-49f7-afe1; __security_mc_1_s_sdk_cert_key=490e3cb6-413b-acb2; __security_mc_1_s_sdk_crypt_sdk=157a90f6-4caa-bd08; __security_server_data_status=1; _tea_utm_cache_1128=undefined; passport_fe_beating_status=false; odin_tt=f2253724dbefb92fbe13ef836a6fa43190a0683ba691cd11fe34a8d9c134af4e975e070ea0837822f0348987d6aa95e4ac389fd0b0d713e3dc52e56be6f0cf3d; gd_random=eyJtYXRjaCI6ZmFsc2UsInBlcmNlbnQiOjAuNzQzNTcxODA1MjAxNjQ3MX0=.4bIx4ulWPDUSOUwlmd5J+dXI/dVZDHUPyh178R9Cpm4=; ttwid=1%7CdW6G4pyoNaDJS48gj7TFfY8z_TFJDxxPIfB3TDR3JNI%7C1776932357%7C1ce0dc2ab274c18cb8ffb707c7564c9dd029e72560cfaca33a7e2cbb8e26da86; bd_ticket_guard_client_data=eyJiZC10aWNrZXQtZ3VhcmQtdmVyc2lvbiI6MiwiYmQtdGlja2V0LWd1YXJkLWl0ZXJhdGlvbi12ZXJzaW9uIjoxLCJiZC10aWNrZXQtZ3VhcmQtcmVlLXB1YmxpYy1rZXkiOiJCRmVlZWJGWEx1ZGRlanpRSjZGRDAxZ2M1UGxvSlNLR1dsTk5mMjU0RmtlZXVsYVZYQ25wbm5STTdsYXVVT0YzQlJZUUhQM2hsSTQ5WE5lSldkdEcrdm89IiwiYmQtdGlja2V0LWd1YXJkLXdlYi12ZXJzaW9uIjoyfQ%3D%3D';

const USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36';

async function test1_validateCookie() {
  console.log('\n===== 测试 1: 验证 Cookie 有效性 =====');
  
  try {
    // 使用创作者中心接口测试
    const response = await axios.get(
      'https://creator.douyin.com/webcast/api/platform_following/outside/room/v1/live_status',
      {
        headers: {
          'accept': 'application/json, text/plain, */*',
          'accept-language': 'zh-CN,zh;q=0.9',
          'appid': '3000',
          'Cookie': TEST_COOKIE,
          'priority': 'u=1, i',
          'referer': 'https://creator.douyin.com/creator-micro/home',
          'sec-ch-ua': '"Chromium";v="140", "Not=A?Brand";v="24", "Google Chrome";v="140"',
          'sec-ch-ua-mobile': '?0',
          'sec-ch-ua-platform': '"Windows"',
          'sec-fetch-dest': 'empty',
          'sec-fetch-mode': 'cors',
          'sec-fetch-site': 'same-origin',
          'user-agent': USER_AGENT,
          'webid': '1156',
          'x-appid': '3000',
          'x-secsdk-csrf-token': '00010000000142644c2227aaed093ff80e3a43964221f0e006f40d9cecdaefd8d4e4645def2118a8ee90760ab3d1',
          'x-sub-web-id': '1156',
        },
        timeout: 10000,
      }
    );

    console.log('✅ Cookie 有效！');
    console.log('状态码:', response.status);
    console.log('响应数据:', JSON.stringify(response.data, null, 2));
    return true;
  } catch (error) {
    console.error('❌ Cookie 验证失败');
    console.error('状态码:', error.response?.status);
    console.error('错误信息:', error.response?.data || error.message);
    return false;
  }
}

async function test2_getUserInfo() {
  console.log('\n===== 测试 2: 获取用户信息 =====');
  
  try {
    const response = await axios.get(
      'https://www.douyin.com/aweme/v1/web/user/profile/self/',
      {
        headers: {
          'accept': 'application/json',
          'Cookie': TEST_COOKIE,
          'referer': 'https://www.douyin.com/',
          'user-agent': USER_AGENT,
        },
        params: {
          'publish_platform': '1',
          'device_platform': 'web',
        },
        timeout: 10000,
      }
    );

    if (response.data?.user?.nickname) {
      console.log('✅ 获取用户信息成功！');
      console.log('用户昵称:', response.data.user.nickname);
      console.log('用户ID:', response.data.user.uid);
      console.log('头像:', response.data.user.avatar_uri);
      return true;
    } else {
      console.log('⚠️ 未获取到用户信息');
      console.log('响应:', JSON.stringify(response.data, null, 2));
      return false;
    }
  } catch (error) {
    console.error('❌ 获取用户信息失败');
    console.error('状态码:', error.response?.status);
    console.error('错误信息:', error.message);
    return false;
  }
}

async function test3_checkUploadAPI() {
  console.log('\n===== 测试 3: 检查视频上传接口 =====');
  
  try {
    // 测试创作者中心的上传接口
    const response = await axios.get(
      'https://creator.douyin.com/web/api/v1/media/upload/video/permission/',
      {
        headers: {
          'accept': 'application/json, text/plain, */*',
          'accept-language': 'zh-CN,zh;q=0.9',
          'Cookie': TEST_COOKIE,
          'referer': 'https://creator.douyin.com/creator-micro/content/publish',
          'sec-ch-ua': '"Chromium";v="140", "Not=A?Brand";v="24", "Google Chrome";v="140"',
          'sec-ch-ua-mobile': '?0',
          'sec-ch-ua-platform': '"Windows"',
          'sec-fetch-dest': 'empty',
          'sec-fetch-mode': 'cors',
          'sec-fetch-site': 'same-origin',
          'user-agent': USER_AGENT,
        },
        timeout: 10000,
      }
    );

    console.log('✅ 上传权限接口可访问');
    console.log('状态码:', response.status);
    console.log('响应数据:', JSON.stringify(response.data, null, 2));
    return true;
  } catch (error) {
    console.error('❌ 上传权限接口测试失败');
    console.error('状态码:', error.response?.status);
    console.error('错误信息:', error.response?.data || error.message);
    
    // 403 或 404 都说明接口存在
    if (error.response?.status === 403 || error.response?.status === 404) {
      console.log('ℹ️  接口存在，但可能需要特定参数或权限');
      return true;
    }
    return false;
  }
}

async function main() {
  console.log('🚀 开始测试抖音发布可行性...\n');
  
  const results = {
    cookieValid: false,
    userInfo: false,
    uploadAPI: false,
  };

  // 测试 1: Cookie 有效性
  results.cookieValid = await test1_validateCookie();
  
  if (!results.cookieValid) {
    console.log('\n❌ Cookie 无效，后续测试取消');
    console.log('\n建议：');
    console.log('1. 重新登录抖音创作者中心');
    console.log('2. 从浏览器重新复制 Cookie');
    console.log('3. 确保复制了完整的 Cookie');
    return;
  }

  // 测试 2: 获取用户信息
  results.userInfo = await test2_getUserInfo();

  // 测试 3: 上传接口
  results.uploadAPI = await test3_checkUploadAPI();

  // 总结
  console.log('\n===== 测试总结 =====');
  console.log('Cookie 有效性:', results.cookieValid ? '✅ 有效' : '❌ 无效');
  console.log('用户信息获取:', results.userInfo ? '✅ 成功' : '❌ 失败');
  console.log('上传接口访问:', results.uploadAPI ? '✅ 可访问' : '❌ 不可访问');

  if (results.cookieValid && results.userInfo) {
    console.log('\n🎉 抖音发布可行性测试通过！');
    console.log('\n接下来可以：');
    console.log('1. 在发布页面绑定抖音账号');
    console.log('2. 粘贴你的 Cookie');
    console.log('3. 尝试发布视频');
  } else {
    console.log('\n⚠️ 部分测试未通过，需要进一步调试');
  }
}

// 运行测试
main().catch(console.error);
