// FILE: _St/IG_StYellow/test_ext_cdp_lifecycle_preload_v281.js | ROLE: v281 CDP 새 문서 unload 선차단·수명주기 로그 회귀 검사
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 content = fs.readFileSync(path.join(root, 'content_instagram.js'), 'utf8');
const auto = fs.readFileSync(path.join(root, '..', 'Auto8700', 'auto_service8700_manager.py'), 'utf8');

assert.strictEqual(manifest.version, '2.3.8.2880');
assert.strictEqual(manifest.version_name, '2.3.8.288');
assert.ok(manifest.description.includes('preloads managed replacement tabs'));

for (const token of [
  '/cdp-bootstrap?token=',
  'YELLOW_CDP_LIFECYCLE_PRELOAD_URL',
  '/api/cdp/ig/install_lifecycle_preload',
  'function igbluePrepareCdpLifecyclePreload',
  '[CDP수명주기][CL-01][체크시작]',
  'chrome.tabs.update(newTabId, {url:targetUrl}',
  'source:"auto8700_cdp_preload_v281"',
  'YELLOW_CDP_LIFECYCLE_DIAG',
  'YELLOW/cdp_lifecycle_diag_v281',
]) assert.ok(background.includes(token), `missing background lifecycle token: ${token}`);

const navStart = background.indexOf('function igblueNavigateActiveWebTab');
const navEnd = background.indexOf('function igblueEnsureContentScripts', navStart);
const nav = background.slice(navStart, navEnd);
const createAt = nav.indexOf('chrome.tabs.create(createProperties');
const preloadAt = nav.indexOf('igbluePrepareCdpLifecyclePreload(bootstrapUrl, targetUrl, meta');
const navigateAt = nav.indexOf('chrome.tabs.update(newTabId, {url:targetUrl}');
const readyAt = nav.indexOf('igblueWaitForNavigationReady(newTabId, targetUrl');
assert.ok(createAt >= 0 && preloadAt > createAt && navigateAt > preloadAt && readyAt > navigateAt,
  'blank create -> CDP preload -> Instagram navigation -> ready order required');

for (const token of [
  'yellow_cdp_lifecycle_diag',
  'yellowForwardCdpLifecycleDiag',
  'type:"YELLOW_CDP_LIFECYCLE_DIAG"',
  '[YELLOW][CDP-LIFECYCLE][BRIDGE_ERROR]',
]) assert.ok(content.includes(token), `missing content lifecycle bridge token: ${token}`);

for (const token of [
  'def cdp_instagram_lifecycle_preload_source',
  'Page.addScriptToEvaluateOnNewDocument',
  "eventType === 'unload'",
  "emit('BLOCKED_REGISTER'",
  "emit('BLOCKED_PROPERTY'",
  "['beforeunload', 'pagehide']",
  'visibilitychange',
  '[CDP수명주기][CL-03][체크완료]',
]) assert.ok(auto.includes(token), `missing Auto8700 lifecycle token: ${token}`);

assert.ok(!auto.includes("eventType === 'beforeunload' && targetKind === 'window' && OPTIONS.block_unload_registration"),
  'beforeunload must be traced, not blocked');
assert.ok(!auto.includes("eventType === 'pagehide' && targetKind === 'window' && OPTIONS.block_unload_registration"),
  'pagehide must be traced, not blocked');

console.log('OK test_ext_cdp_lifecycle_preload_v281');
