import { expect } from 'e2e';
import { readFile, writeFile, utimes } from 'node:fs/promises';
import { setTimeout as delay } from 'node:timers/promises';
import { T3_HOME, APP_DIR } from '../e2e.config.ts';
import { test, WEB, makeState, runPromise } from './t3.ts';

test('Invalid settings must not settle two idle threads', WEB, async ({t3, app, screen}) => {
 const settingsPath = `${T3_HOME}/userdata/settings.json`;
 await writeFile('/tmp/factory-issue-46001-evidence-1/offset', String(-8*86400000));
 const project = await t3.project('Idle work');
 await delay(5000);
 const first = await t3.thread({project, title:'Idle thread alpha', messages:['Start'], model:'multi-turn'});
 await t3.thread({project, title:'Idle thread beta', messages:['Start'], model:'multi-turn'});
 const settings = {...JSON.parse(await readFile(settingsPath,'utf8')), sidebarAutoSettleAfterDays:null, sidebarAutoSettleOnMerge:false};
 const valid = JSON.stringify(settings,null,2);
 await writeFile(settingsPath,valid);
 await delay(1500);
 const previousRuntime = JSON.parse(await readFile(`${T3_HOME}/userdata/server-runtime.json`,'utf8'));
 await writeFile('/tmp/factory-issue-46001-evidence-1/offset','0');
 // The development watcher restarts its server when an entrypoint timestamp changes.
 await utimes(`${APP_DIR}/apps/server/src/bin.ts`, new Date(), new Date());
 await delay(5000);
 const restartedRuntime = JSON.parse(await readFile(`${T3_HOME}/userdata/server-runtime.json`,'utf8'));
 if (restartedRuntime.startedAt === previousRuntime.startedAt) throw new Error('Server did not restart on the real clock');
 await delay(15000);
 await t3.open(first);
 await screen.getByRole('textbox').waitFor({timeout:120000});
 await screen.getByText('Syncing messages...').waitFor({state:'hidden'});
 const baseline = JSON.parse((await runPromise(makeState(T3_HOME).cli(['thread','list','--project',project,'--json']))).stdout);
 if (baseline.length !== 2 || baseline.some((row: {settled:boolean}) => row.settled)) throw new Error('Setup did not leave two idle threads unsettled');
 await app.screenshot('auto-settle-disabled');
 await writeFile(settingsPath,valid.slice(0,-1));
 await delay(3000);
 await app.screenshot('invalid-settings');
 await writeFile(settingsPath,valid);
 await delay(3000);
 await app.screenshot('restored-settings');
 const {stdout} = await runPromise(makeState(T3_HOME).cli(['thread','list','--project',project,'--json']));
 const listed = JSON.parse(stdout);
 const rows = Array.isArray(listed) ? listed : listed.threads;
 await expect(rows.map((row: {settled:boolean})=>row.settled)).toEqual([false,false]);
});
