// FILE: _St/IG_StYellow/test_ext_auto_wait_resume.js | ROLE: IG_StYellow 회귀 테스트
const fs = require('fs');
const path = require('path');
const assert = require('assert');
const root = __dirname;
const side = fs.readFileSync(path.join(root, 'side.js'), 'utf8');
const html = fs.readFileSync(path.join(root, 'side.html'), 'utf8');
const manifest = JSON.parse(fs.readFileSync(path.join(root, 'manifest.json'), 'utf8'));

assert.strictEqual(manifest.version, '2.3.8.3190');
assert.strictEqual(manifest.version_name, '2.3.8.319');
assert.ok(side.includes('const IGBLUE_PACKAGE_VERSION = IGBLUE_BUILD_TAG;'));

// One active Instagram tab is captured at new-session start and reused during account continuation.
for (const token of [
  'let teAutoPySessionTarget = { active: false',
  'async function teAutoPyAcquireStartTab(mySeq)',
  'async function teAutoPyProbeSessionTarget(mySeq)',
  'async function teAutoPyWaitForSessionTarget(mySeq, waitRequired)',
  'teAutoPyStartOnceFromUi({ new_session: false, continuation: true',
  'teAutoPyUiReset(targetLimit, newSession ? "자동 시작" : "다음 계정 계속", { reset_run_totals: newSession })'
]) assert.ok(side.includes(token), `missing start-tab/session token: ${token}`);

// Recoverable states wait forever and resume from the same state.
for (const token of [
  'user_window_in_use',
  'auto_start_tab_non_instagram',
  'ws8771_disconnected',
  'main_injection_not_ready',
  'NoNav_Current_missing',
  'no_rank_labels',
  'teAutoPyEnterWait(',
  'teAutoPyLeaveWait(',
  '조건이 정상화되면 같은 단계에서 자동으로 이어서 실행합니다.'
]) assert.ok(side.includes(token), `missing wait/resume token: ${token}`);
assert.ok(side.includes('for (;;)') && side.includes('WS8771 연결이 끊어져 정상화를 기다리는 중입니다.'));
assert.ok(side.includes('while (!runSeq || runSeq === teAutoPyRunSeq)'));
for (const token of [
  'function teAutoPyWsTemporaryFailure(value)',
  'async function teAutoPyWaitForWsRetry(seq, message)',
  'AUTO_DIRECT_WS_NOT_READY',
  'IGBLUE_WS_NOT_READY',
  'WS8771 중복 확인 연결이 끊어져 같은 게시물에서 정상화를 기다리는 중입니다.',
  'WS8771 다운로드 연결이 끊어져 같은 파일에서 정상화를 기다리는 중입니다.',
  'stopped_while_waiting_ws'
]) assert.ok(side.includes(token), `missing WS operation retry token: ${token}`);

// Closing the captured start tab is fatal; merely changing its URL is not.
assert.ok(side.includes('return { ok: false, fatal: true, error: "auto_start_tab_closed" }'));
assert.ok(side.includes('return { ok: false, wait: true, error: "auto_start_tab_non_instagram"'));
assert.ok(side.includes('S00_AUTOPLAY_START_TAB_CLOSED'));

// Existing _St.zip notice area becomes the visible wait/resume/stop surface.
for (const token of [
  'id="igblue_aiwk_setup_default"',
  'id="igblue_auto_runtime_notice"',
  'id="igblue_auto_runtime_notice_title"',
  'id="igblue_auto_runtime_notice_text"',
  'is-auto-wait',
  'is-auto-resume',
  'is-auto-stop',
  'aria-live="assertive"'
]) assert.ok(html.includes(token), `missing runtime notice UI token: ${token}`);
assert.ok(!side.includes('alert('), 'modal alert must not interrupt infinite wait');

// Whole-run totals reset only for a new session; account continuation keeps them.
assert.ok(side.includes('if (opts.reset_run_totals !== false) teAutoPyRunTotals ='));
assert.ok(side.includes('{ reset_run_totals: newSession }'));
assert.ok(side.includes('new_session: false, continuation: true'));

// Queue end is guarded by the real index and the next run index is reset separately.
assert.ok(side.includes('const queueComplete ='));
assert.ok(side.includes('!!info.queue_completed'));
assert.ok(side.includes('queue_completed: true'));
assert.ok(side.includes('if (urls.length) teAutoPySetAccountQueueIndex(0);'));
assert.ok(side.includes('const nextUiIndex = currentUiIndex + 1;'));
assert.ok(side.includes('if (nextUiIndex > urls.length)'));

// UI order and line preservation.
const lastRankAt = html.indexOf('id="igblue_auto_py_last_rank"');
const pyAt = html.indexOf('id="igblue_py_status"');
const startAt = html.indexOf('id="igblue_auto_py_start"');
assert.ok(lastRankAt >= 0 && pyAt > lastRankAt && startAt > pyAt, 'recent point -> Py/Auto PY -> auto start order must be preserved');
assert.ok(html.includes('white-space: pre-line;'));

console.log('OK test_ext_auto_wait_resume v272');
