/// <reference lib="dom" />
import { readFile, readdir, writeFile, mkdir } from 'node:fs/promises';
import { expect } from 'e2e';
import { T3_HOME } from '../e2e.config.ts';
import { test, WEB } from './t3.ts';

const frame = '  1%|#                                                                       | 1/100 [00:01<01:39,  1.00it/s]\r';
const last = '100%|########################################################################| 100/100 [01:40<00:00,  1.00it/s]\n';
const notebook = JSON.stringify({ nbformat: 4, nbformat_minor: 5, metadata: {}, cells: [
  {cell_type:'code', metadata:{}, execution_count:1, source:['train()'], outputs:[{output_type:'stream',name:'stderr',text:[frame.repeat(50000)+last]}]},
  {cell_type:'markdown', metadata:{}, source:['Later cell survived']}
]});

test('Notebook attachment extraction keeps the final progress frame and later cell', WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project('notebook-proof', {'progress.ipynb':notebook, 'extraction-report.txt':'Waiting for upload'});
  const thread = await t3.thread({project, title:'Notebook attachment extraction', messages:['Start'], model:'multi-turn'});
  await browser.setViewport({width:1440,height:1080});
  await t3.open(thread);
  await screen.getByText('first fixture turn complete', {exact:false}).waitFor();
  await screen.getByRole('textbox').fill('Read the extracted .txt attachment of this notebook. Report the final progress line, intermediate 1% frames, the later markdown cell, and truncation.');
  await browser.evaluate((content) => {
    const clipboardData = new DataTransfer();
    clipboardData.items.add(new File([content], 'progress.ipynb', {type:'application/x-ipynb+json'}));
    const editor = document.querySelector('[contenteditable="true"]');
    if (!editor) throw new Error('No composer');
    editor.dispatchEvent(new ClipboardEvent('paste',{clipboardData,bubbles:true,cancelable:true}));
  }, notebook);
  await screen.getByRole('button', 'progress.ipynb', {exact:false}).first().waitFor();
  await screen.getByRole('textbox').press('Enter');
  await screen.getByText('second fixture turn complete', {exact:false}).waitFor({timeout:120000});
  const files = await readdir(`${T3_HOME}/userdata/attachments`, {recursive:true});
  const sidecar = files.find(f => f.endsWith('.ipynb.txt'));
  if (!sidecar) throw new Error(`No extracted sidecar: ${files.join(', ')}`);
  const text = await readFile(`${T3_HOME}/userdata/attachments/${sidecar}`, 'utf8');
  const report = [
    'NOTEBOOK ATTACHMENT — REAL SERVER EXTRACTION',
    'Source: uploaded progress.ipynb, 50,000 carriage-return redraws + final frame.',
    'Measured from the server-generated .ipynb.txt, not from Replay reply.',
    '',
    `Extracted characters: ${text.length}`,
    `Final 100% frame present: ${text.includes('100%|')}`,
    `Intermediate 1% frames: ${(text.match(/  1%\|/g)||[]).length}`,
    `Later markdown cell present: ${text.includes('Later cell survived')}`,
    `Truncation notice present: ${text.includes('[Extracted text truncated')}`,
    '', '--- First 230 characters of actual sidecar ---', text.slice(0,230),
    '', '--- Last 230 characters of actual sidecar ---', text.slice(-230),
  ].join('\n');
  await writeFile(`${project}/extraction-report.txt`, report);
  const output = `/tmp/factory-pr-42272-evidence-1/run-${Date.now()}`;
  await mkdir(output, {recursive:true});
  await writeFile(`${output}/extracted.txt`,text);
  await writeFile(`${output}/report.txt`,report);
  await browser.keyboard.press('Control+p');
  await screen.getByPlaceholder('Search files…').fill('extraction-report.txt');
  await screen.getByRole('option','extraction-report.txt',{exact:false}).tap();
  await browser.locator('[data-file-crumb]').first().waitFor();
  await screen.getByRole('button', 'Maximize panel').tap();
  await expect.poll(() => browser.evaluate(() => {
    for (const host of document.querySelectorAll('*')) {
      const content = host.shadowRoot?.querySelector('[data-content]');
      if (content?.textContent?.includes('NOTEBOOK ATTACHMENT')) return content.textContent;
    }
    return '';
  }), {timeout:120000}).toContain('Truncation notice present:');
  await app.screenshot('extracted-attachment-report');
  expect(text.includes('100%|')).toBe(true);
  expect(text).not.toContain('  1%|');
  expect(text).toContain('Later cell survived');
  expect(text).not.toContain('[Extracted text truncated');
});
