import { readFileSync, writeFileSync, utimesSync } from 'node:fs';
import { ProjectSnapshot, ProviderInstanceId } from '@t3tools/contracts';
import { expect } from 'e2e';
import * as Effect from 'effect/Effect';
import * as Stream from 'effect/Stream';
import * as Option from 'effect/Option';
import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from 'effect/http';
import { T3_HOME, APP_DIR } from '../e2e.config.ts';
import { makeState, rpcClient, runPromise, test, WEB } from './t3.ts';

test('A current daily slot runs after an earlier slot was missed during downtime', WEB, async ({t3, app, screen}) => {
 await t3.project('daily-task-proof');
 await runPromise(Effect.gen(function* () {
  const issued = yield* makeState(T3_HOME).cli(['auth','session','issue','--token-only']);
  const {projects} = yield* HttpClient.execute(HttpClientRequest.get(`${app.baseUrl}/api/projects`).pipe(HttpClientRequest.bearerToken(issued.stdout.trim()))).pipe(Effect.flatMap(HttpClientResponse.filterStatusOk),Effect.flatMap(HttpClientResponse.schemaBodyJson(ProjectSnapshot)));
  const client = yield* rpcClient(T3_HOME, app.baseUrl ?? '');
  yield* client['scheduledTasks.upsert']({title:'Daily 09:00 downtime proof',prompt:'Describe the recorded demo.',enabled:true,schedule:{type:'fixed_time',timeOfDay:'09:00'},projectId:projects.find(p=>p.title==='daily-task-proof')!.id,workspaceStrategy:{type:'root'},modelSelection:{instanceId:ProviderInstanceId.make('devReplay'),model:'showcase'},runtimeMode:'full-access',interactionMode:'default'});
 }).pipe(Effect.scoped,Effect.provide(FetchHttpClient.layer)));
 await t3.open('/settings/scheduled-tasks');
 await screen.getByText('Daily 09:00 downtime proof',{exact:true}).waitFor();
 await app.screenshot('before-downtime');
 const root=process.env.PROOF_DIR!;
 const pid=Number(readFileSync(root+'/server.pid','utf8'));
 process.kill(pid,'SIGKILL');
 writeFileSync(root+'/clock.txt','2026-12-04T09:05:00Z');
 // Wake the development launcher after stopping its own captured server process.
 const realNow=new Date();
 utimesSync(APP_DIR+'/apps/server/src/bin.ts',realNow,realNow);
 // Both outcomes are final visible scheduler states; the assertion below distinguishes them.
 await screen.getByText(/Missed a scheduled run because|Succeeded/, {exact:false}).first().waitFor();
 try { await expect(screen.getByText('Missed a scheduled run because the server was not running at that time.',{exact:true})).not.toBeVisible(); }
 finally {await app.screenshot('current-slot-after-downtime');}
 const task = await runPromise(Effect.gen(function* () {
  const client=yield* rpcClient(T3_HOME,app.baseUrl ?? '');
  const snapshot=yield* client['scheduledTasks.subscribe']({}).pipe(Stream.runHead);
  return Option.getOrThrow(snapshot).tasks.find(t=>t.title==='Daily 09:00 downtime proof')!;
 }).pipe(Effect.scoped));
 await expect(task.runCount).toBe(1);
 await expect(task.nextRunAt).toBe('2026-12-05T09:00:00.000Z');
});
