/**
 * SET 56c — surface contract tests (S6/S7/S8 + R5/R8 + stale-banner wiring).
 */
import { describe, expect, it } from 'vitest';
import fs from 'node:fs';
import path from 'node:path';

const APP = path.resolve(import.meta.dirname, '../web/src/App.tsx');

function appSrc(): string {
  return fs.readFileSync(APP, 'utf8');
}

/** Tier1View body only — excludes AdminView / InstallStatsPanel overlays. */
function runViewSrc(): string {
  const src = appSrc();
  const start = src.indexOf('function Tier1View');
  const end = src.indexOf('export function App');
  expect(start).toBeGreaterThan(0);
  expect(end).toBeGreaterThan(start);
  return src.slice(start, end);
}

describe('SET 56c T1 — stale-banner App wiring (SET 50 restore)', () => {
  it('App.tsx polls ~2min and shows the banner copy', () => {
    const src = appSrc();
    expect(src).toContain('STALE_BUNDLE_POLL_MS');
    expect(src).toContain('STALE_BUNDLE_BANNER');
    expect(src).toContain('shouldShowStaleBundleBanner');
    expect(src).toContain('/version.json');
    expect(src).toContain('stalebanner');
  });
});

describe('SET 56c T2 — set56-surface', () => {
  it('S6 localStorage keys + S8 boot markers + R5 epoch-header + R8 helpers', () => {
    const src = appSrc();
    expect(src).toContain('rha.collapse.pipelineLog');
    expect(src).toContain('rha.collapse.prompt');
    expect(src).toContain('data-rha-boot="control-prompt"');
    expect(src).toContain('data-rha-boot="control-compile"');
    // R5 epoch header format pieces
    expect(src).toContain('toLocaleString()');
    expect(src).toMatch(/#\$\{epIdx \+ 1\} · \$\{new Date\(ep\.ts\)\.toLocaleString\(\)/);
    // R8 helpers
    expect(src).toContain('emptyPipelineLogLabel');
    expect(src).toContain('RUN_RECORD_MISSING');
    expect(src).toContain('isCheckpointedUnfinalized');
    expect(src).toContain('formatCheckpointHeader');
    expect(src).toContain('formatRelOffset');
    expect(src).toContain('isSubstrateEvent');
  });
});

describe('SET 56c T3 — S7 no install-lifetime in run view', () => {
  it('run-view source has no install-lifetime / GLOBAL scope', () => {
    const runView = runViewSrc();
    // Install-lifetime copy + stats:local poll must not live in Tier1View.
    expect(runView).not.toMatch(/this install/);
    expect(runView).not.toContain('stats:local');
    expect(runView).not.toContain('setGlobalStats');
    expect(runView).not.toContain('InstallStatsPanel');
    // FacetCell project-total column key remains (R10 / T4) — that is not
    // install-lifetime scope. Assert the install GLOBAL block is gone:
    expect(runView).not.toMatch(/<b[^>]*>global<\/b>/);
  });
});
