import * as fs from 'node:fs/promises';
import * as path from 'node:path';
import { execFileSync } from 'node:child_process';
import { expect } from 'e2e';
import { T3_HOME } from '../e2e.config.ts';
import { makeState, runPromise, test, WEB } from './t3.ts';

test('Older Pi conversation survives 100 unreadable newer sessions and a retry', WEB, async ({t3, app, screen, browser}) => {
  const root = process.env.PI_CODING_AGENT_SESSION_DIR!;
  const workspace = path.join(root, '..', 'workspace');
  await fs.mkdir(root, {recursive:true});
  await fs.mkdir(workspace, {recursive:true});
  await fs.writeFile(path.join(workspace,'README.md'), 'Synthetic import evidence\n');
  execFileSync('git', ['init','--quiet','--initial-branch=main'], {cwd:workspace});
  const now = Date.now();
  for (let i=0;i<101;i++) {
    const id = `session-${String(i).padStart(3,'0')}`;
    const prompt = i === 100 ? 'Review the older readable conversation' : `Review newer conversation ${i}`;
    const records: unknown[] = [
      {type:'session',version:3,id,cwd:workspace,timestamp:new Date(now-(i+1)*60000).toISOString()},
      {type:'message',id:'u1',parentId:null,message:{role:'user',content:prompt}},
      {type:'message',id:'a1',parentId:'u1',message:{role:'assistant',content:[{type:'text',text:i===100?'The older conversation is readable and should remain reachable.':'Newer reply'}]}},
    ];
    if(i<100) {
      let details: unknown = {result:'synthetic'};
      for(let d=0;d<130;d++) details={nested:details};
      records.push({type:'message',id:'a2',parentId:'a1',message:{role:'assistant',content:[{type:'toolCall',id:'tool1',name:'read',arguments:{path:'README.md'}}]}});
      records.push({type:'message',id:'t1',parentId:'a2',message:{role:'toolResult',toolCallId:'tool1',toolName:'read',content:[{type:'text',text:'Synthetic result'}],details,isError:false}});
    }
    const file=path.join(root,`${id}.jsonl`);
    await fs.writeFile(file,records.map(r=>JSON.stringify(r)).join('\n')+'\n');
    await fs.utimes(file,new Date(now-(i+1)*60000),new Date(now-(i+1)*60000));
  }
  const capture = async (label: string) => {
    await browser.evaluate(async () => {
      await Promise.all(document.getAnimations().filter(a => a.effect?.getTiming().iterations !== Infinity).map(a => a.finished.catch(() => undefined)));
      return null;
    });
    await app.screenshot(label);
    // Hold completed screens so both import attempts are readable in the evidence recording.
    await browser.evaluate(async () => { await new Promise(resolve => setTimeout(resolve, 1500)); return null; });
  };
  await browser.setViewport({width:1440,height:1000});
  await t3.open('/welcome');
  await screen.getByRole('button', /Add more agents|Set up an agent/).tap();
  await screen.getByRole('button','Turn on: Pi',{exact:true}).tap();
  await screen.getByText('Checking Pi CLI availability…',{exact:true}).waitFor({state:'hidden'});
  await screen.getByRole('button', /Review all/).tap();
  await screen.getByRole('button','Select none',{exact:true}).tap();
  await screen.getByRole('button','Select all',{exact:true}).tap();
  await capture('pi-first-review-101');
  await screen.getByRole('button','Import 1 project and start',{exact:true}).tap();
  await screen.getByText(/threads could not be imported/).waitFor();
  await capture('pi-first-import');
  await t3.open('/settings/about');
  await screen.getByRole('link','Open',{exact:true}).waitFor();
  await capture('pi-retry-settings-about');
  await screen.getByRole('link','Open',{exact:true}).tap();
  await screen.getByRole('button',/Review all/).tap();
  const selectAll=screen.getByRole('button','Select all',{exact:true});
  // Existing projects are unselected when reopening Welcome.
  await selectAll.tap();
  await capture('pi-retry-review');
  await screen.getByRole('button',/Import .* and start/).tap();
  await screen.getByText(/threads could not be imported/).waitFor();
  await capture('pi-retry-import');
  const listed=await runPromise(makeState(T3_HOME).cli(['thread','list','--project',workspace,'--json']));
  const threads=JSON.parse(listed.stdout) as Array<{threadId?:string;id?:string;title:string}>;
  const older=threads.find(t=>t.title==='Review the older readable conversation');
  if(older) {
    await t3.open({threadId:older.threadId??older.id!});
    await screen.getByText('The older conversation is readable and should remain reachable.',{exact:true}).waitFor();
    await capture('pi-older-conversation');
  }
  expect(older,'Older readable session must be imported despite 100 newer unreadable sessions').toBeDefined();
});
