const fs = require('fs');
const path = require('path');
const https = require('https');
const http = require('http');

const VIDEO_URL = 'https://ark-acg-cn-beijing.tos-cn-beijing.volces.com/doubao-seedance-2-0/02178127238246100000000000000000000ffffac15e016345dd1.mp4?X-Tos-Algorithm=TOS4-HMAC-SHA256&X-Tos-Credential=AKLTYWJkZTExNjA1ZDUyNDc3YzhjNTM5OGIyNjBhNDcyOTQ%2F20260612%2Fcn-beijing%2Ftos%2Frequest&X-Tos-Date=20260612T135533Z&X-Tos-Expires=86400&X-Tos-Signature=272274c8f3c603cb08a0f1ee2d2c4f81344802e5c20b34fd7d77d9cfaf45f172&X-Tos-SignedHeaders=host';

const OUT = path.resolve(__dirname, '../outputs/shots/ep01-shot01-v2.mp4');

const dir = path.dirname(OUT);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });

console.log('📥 下载镜1视频...');

const urlObj = new URL(VIDEO_URL);
const transport = urlObj.protocol === 'https:' ? https : http;

const file = fs.createWriteStream(OUT);
transport.get(VIDEO_URL, (res) => {
  if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
    const redir = res.headers.location.startsWith('http')
      ? res.headers.location
      : `${urlObj.protocol}//${urlObj.host}${res.headers.location}`;
    console.log('↪ 跟随重定向...');
    const transport2 = new URL(redir).protocol === 'https:' ? https : http;
    transport2.get(redir, (res2) => {
      res2.pipe(file);
      file.on('finish', () => {
        const stat = fs.statSync(OUT);
        console.log(`✅ 下载完成: ${OUT}`);
        console.log(`   文件大小: ${(stat.size / 1024).toFixed(1)} KB`);
      });
    });
    return;
  }
  res.pipe(file);
  file.on('finish', () => {
    const stat = fs.statSync(OUT);
    console.log(`✅ 下载完成: ${OUT}`);
    console.log(`   文件大小: ${(stat.size / 1024).toFixed(1)} KB`);
  });
});
