// FILE: _St/IG_StYellow/test_ext_account_queue_v273.js | ROLE: IG_StYellow 회귀 테스트
const assert = require('assert');
const fs = require('fs');
const path = require('path');
const vm = require('vm');

const root = __dirname;
const manifest = JSON.parse(fs.readFileSync(path.join(root, 'manifest.json'), 'utf8'));
const sideHtml = fs.readFileSync(path.join(root, 'side.html'), 'utf8');
const side = fs.readFileSync(path.join(root, 'side.js'), 'utf8');
const bg = fs.readFileSync(path.join(root, 'background.js'), 'utf8');
const content = fs.readFileSync(path.join(root, 'content_instagram.js'), 'utf8');

assert.strictEqual(manifest.version, '2.3.8.2920');
assert.strictEqual(manifest.version_name, '2.3.8.292');
assert.ok(side.includes('const IGBLUE_PACKAGE_VERSION = "v292";'));

// 1/N 이상은 새 비활성 탭을 만들고 준비 확인 뒤 이전 탭을 닫는다.
assert.ok(bg.includes('IGBLUE_NAVIGATE_ACTIVE_TAB'));
assert.ok(bg.includes('chrome.tabs.create(createProperties'));
assert.ok(bg.includes('igblueWaitForNavigationReady(newTabId, targetUrl'));
assert.ok(bg.includes('function igblueCloseManagedAutoTab') && bg.includes('igblueRequestCdpTargetClose'));
assert.ok(side.includes('계정 ${freshStartTarget.index}/${freshStartTarget.total} 새 탭 로드'));
assert.ok(side.includes('type: "IGBLUE_NAVIGATE_ACTIVE_TAB", url: freshStartTarget.url'));
assert.ok(side.includes('function teAutoPyFreshStartPreview()'));

// 0/N도 Explore/current-page snapshot을 쓰지 않고 목록 1번을 새 자동 탭으로 시작한다.
assert.ok(side.includes('let desiredIndex = uiIndex <= 0 ? 1'));
assert.ok(side.includes('목록 첫 계정을 새 자동 탭에서 시작'));

// 삭제 계정은 명시적 not_found만 휴지통+SQLite 저장 후 같은 index의 다음 활성 URL로 넘어간다.
assert.ok(content.includes('igblue_get_account_page_state'));
assert.ok(side.includes('S00_ACCOUNT_DELETED_TOMBSTONE'));
assert.ok(side.includes('🗑️ @${normalized}'));
assert.ok(side.includes('if (nav && nav.deleted_account && nav.tombstone_saved) continue;'));
assert.ok(side.includes('explicit_not_found === true'));

// SQLite 파일 전환 UI/API.
for (const id of ['igblue_account_db_filename','igblue_account_db_open','igblue_account_db_new','igblue_account_db_save_as','igblue_account_db_status']) {
  assert.ok(sideHtml.includes(`id="${id}"`), `${id} missing`);
}
assert.ok(side.includes('/api/database-files'));
assert.ok(side.includes('/api/database/${endpoint}'));
assert.ok(side.includes('account_database_${action}'));

// content page-state classifier 실행 검증.
const start = content.indexOf('function igblueReadAccountPageState(expectedUsername)');
const end = content.indexOf('try { globalThis.__IGBLUE_V273_ACCOUNT_PAGE_STATE_TEST__', start);
assert.ok(start >= 0 && end > start, 'account page state helper block missing');
const helperCode = content.slice(start, end) + '\nthis.readState = igblueReadAccountPageState;';
function classify({href, text}) {
  const context = {
    URL,
    location: { href },
    document: { body: { innerText: text, textContent: text } },
    Set,
  };
  vm.runInNewContext(helperCode, context, {filename:'account_page_state_v273.js'});
  return context.readState('gone_account');
}
let state = classify({href:'https://www.instagram.com/gone_account/', text:"Sorry, this page isn't available. The link you followed may be broken, or the page may have been removed."});
assert.strictEqual(state.state, 'not_found');
assert.strictEqual(state.explicit_not_found, true);
state = classify({href:'https://www.instagram.com/gone_account/', text:'This account is private. Follow to see their photos and videos.'});
assert.strictEqual(state.state, 'private');
assert.strictEqual(state.explicit_not_found, false);
state = classify({href:'https://www.instagram.com/accounts/login/', text:'Log in to Instagram'});
assert.strictEqual(state.state, 'auth_required');
assert.strictEqual(state.explicit_not_found, false);
state = classify({href:'https://www.instagram.com/other_account/', text:"Sorry, this page isn't available."});
assert.strictEqual(state.state, 'navigating');
assert.strictEqual(state.explicit_not_found, false);

console.log('OK test_ext_account_queue_v273');
