// FILE: _St/IG_StYellow/test_ext_auto_fresh_tab_cdp_close_v287.js | ROLE: v287 자동 새 탭·CDP 강제 종료·다운로드 분리 회귀 검사
const assert = require('assert');
const fs = require('fs');
const path = require('path');

const ROOT = __dirname;
const manifest = JSON.parse(fs.readFileSync(path.join(ROOT, 'manifest.json'), 'utf8'));
const background = fs.readFileSync(path.join(ROOT, 'background.js'), 'utf8');
const side = fs.readFileSync(path.join(ROOT, 'side.js'), 'utf8');

assert.strictEqual(manifest.version, '2.3.8.2870');
assert.strictEqual(manifest.version_name, '2.3.8.287');
assert.ok(manifest.description.includes('proven v279c WS8771 direct MP4/JPG path'));
assert.ok(manifest.description.includes('Target.closeTarget'));

for (const token of [
  'YELLOW_CDP_CLOSE_TARGET_URL',
  '/api/cdp/ig/close_target',
  'function igblueRequestCdpTargetClose',
  'function igblueCloseManagedAutoTab',
  'meta.auto_created !== true',
  'cdp_target_id:cdpTargetId',
  'auto_created:true',
  'IGBLUE_CLOSE_MANAGED_AUTO_TAB',
  '[CDP탭종료][TC-01]',
  '[CDP탭종료][TC-02]',
  'fallback:"chrome.tabs.remove"',
  'tab_verified_removed:true',
  'target 제거 후 Chrome tab 잔존'
]) assert.ok(background.includes(token), `missing background token: ${token}`);

const closeBlock = background.slice(
  background.indexOf('function igblueCloseManagedAutoTab'),
  background.indexOf('function igblueClosePreviousTabAfterReplacement')
);
assert.ok(closeBlock.includes('igblueRequestCdpTargetClose'));
assert.ok(closeBlock.indexOf('igblueRequestCdpTargetClose') < closeBlock.indexOf('fallbackRemove(cdpResult'));
assert.ok(closeBlock.includes('reason:"not_managed_auto_tab"'));

for (const token of [
  'function teAutoPyFreshStartPreview',
  'forced_first_account: true',
  'let desiredIndex = uiIndex <= 0 ? 1',
  '자동 시작 시 목록 1/${urls.length}부터 새 탭',
  'reason: "auto_start_current_page_fresh_tab"',
  'type: "IGBLUE_CLOSE_MANAGED_AUTO_TAB"',
  'reason: "automatic_end"',
  'S00_AUTO_TAB_FORCE_CLOSE',
  'const IGBLUE_PACKAGE_VERSION = "v287";'
]) assert.ok(side.includes(token), `missing side token: ${token}`);

// v282 split download contract must remain: automatic uses WS direct, manual keeps MANUAL_SINGLE path.
for (const token of [
  'teAutoPyDirectDownloadAsset',
  'teAutoPyDownloadMediaPairDirect',
  'ig_media_download_direct',
  'MANUAL_SINGLE'
]) assert.ok(side.includes(token) || background.includes(token), `missing split-download token: ${token}`);

assert.ok(side.includes('id="igblue_account_queue_start_one"') || fs.readFileSync(path.join(ROOT, 'side.html'), 'utf8').includes('id="igblue_account_queue_start_one"'));
console.log('OK test_ext_auto_fresh_tab_cdp_close_v287');
