// FILE: _St/IG_StYellow/test_ext_chrome_session_download_v283.js | ROLE: v283 Chrome 세션 자동·수동 다운로드 후 WS8771 이동 회귀 검사
const fs = require('fs');
const path = require('path');
const assert = require('assert');
const root = __dirname;
const bg = fs.readFileSync(path.join(root, 'background.js'), 'utf8');
const side = fs.readFileSync(path.join(root, 'side.js'), 'utf8');
const manifest = JSON.parse(fs.readFileSync(path.join(root, 'manifest.json'), 'utf8'));
assert.strictEqual(manifest.version, '2.3.8.2830');
assert.strictEqual(manifest.version_name, '2.3.8.283');
assert.ok(side.includes('const IGBLUE_PACKAGE_VERSION = "v283";'));
const start = bg.indexOf('function igblueDownloadWithApi(msg, sendResponse)');
const end = bg.indexOf('function igblueIsInstagramUrl(url)', start);
assert.ok(start >= 0 && end > start);
const block = bg.slice(start, end);
for (const token of [
  'chrome.downloads.download({url, filename:tempFile, saveAs:false, conflictAction:"uniquify"}',
  'const tempFile = `YELLOW_TEMP/',
  'item.state !== "complete"',
  'igblueLocalWsRequest("ig_media_downloaded"',
  'filename:originalFileName',
  'file_path:tempPath',
  'igbluePollWsQueuedJob(queuedFinalize.job_id',
  'message:"Chrome session download · WS8771 move complete"',
  'chrome_session_download:true',
  'ws_relocated:true'
]) assert.ok(block.includes(token), token);
assert.ok(!block.includes('ig_media_download_direct'));
assert.ok(!block.includes('urllib'));
assert.ok(manifest.permissions.includes('downloads'));
console.log('OK test_ext_chrome_session_download_v283');

(async () => {
  const vm = require('vm');
  const events = [];
  let requested = null;
  let polled = '';
  const sandbox = {
    console,
    URL,
    Date,
    Math,
    Promise,
    setInterval(fn) { Promise.resolve().then(fn); return 71; },
    clearInterval() {},
    dbg() {},
    igblueGuessExt() { return 'mp4'; },
    igblueNormalizeDownloadPrefix() { return 'owner_No001_CODE'; },
    igblueOwnerFromDownloadMsg() { return 'owner'; },
    igblueOriginalDownloadFileName() { return 'instagram_original.mp4'; },
    igblueSafePath(v) { return String(v); },
    igblueSafeFileName(v) { return String(v); },
    igblueMetaShortcode() { return 'CODE'; },
    igblueAssetKindFromMeta() { return 'video'; },
    igblueSendDownloadProgress(v) { events.push(v); },
    igblueSendFeatureCheck() {},
    igblueLocalWsRequest(act, data) {
      requested = {act, data};
      return Promise.resolve({ok:true, job_id:'JOB1'});
    },
    igbluePollWsQueuedJob(jobId) {
      polled = jobId;
      return Promise.resolve({
        ok:true,
        file_path:'D:\\_StDown\\instagram\\owner\\instagram_original.mp4',
        size:1234,
        storage_ok:true,
        json_path:'D:\\_StDown\\instagram\\owner.json',
        report_ok:true,
        report_path:'D:\\_StDown\\instagram\\owner.html',
        media_saved:{event_id:'E1'}
      });
    },
    chrome: {
      runtime: {lastError:null},
      downloads: {
        download(options, cb) { sandbox.downloadOptions = options; cb(7); },
        search(query, cb) { cb([{id:7,state:'complete',filename:'C:\\Users\\tester\\Downloads\\YELLOW_TEMP\\temp.mp4',bytesReceived:1234,totalBytes:1234}]); }
      }
    }
  };
  vm.createContext(sandbox);
  vm.runInContext(`${block}; this.runDownload = igblueDownloadWithApi;`, sandbox);
  const response = await new Promise((resolve, reject) => {
    sandbox.runDownload({
      url:'https://cdn.example/media.mp4',
      account:'owner',
      auto_direct_download:true,
      href:'https://www.instagram.com/reel/CODE/',
      meta:{shortcode:'CODE',owner_username:'owner',asset_kind:'video',media_index:0,source_mode:'TOP_SORTED'}
    }, resolve);
    setTimeout(() => reject(new Error('download simulation timeout')), 1000);
  });
  assert.strictEqual(sandbox.downloadOptions.saveAs, false);
  assert.ok(String(sandbox.downloadOptions.filename).startsWith('YELLOW_TEMP/'));
  assert.strictEqual(requested.act, 'ig_media_downloaded');
  assert.strictEqual(requested.data.filename, 'instagram_original.mp4');
  assert.ok(requested.data.file_path.includes('YELLOW_TEMP'));
  assert.strictEqual(polled, 'JOB1');
  assert.strictEqual(response.status, 'ok');
  assert.strictEqual(response.chrome_session_download, true);
  assert.strictEqual(response.ws_relocated, true);
  assert.strictEqual(response.file_path, 'D:\\_StDown\\instagram\\owner\\instagram_original.mp4');
  assert.ok(events.some((e) => e.status === 'done' && String(e.message).includes('WS8771 move complete')));
  console.log('OK test_ext_chrome_session_download_v283 simulation');
})().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});
