import * as fs from 'node:fs/promises';
import * as path from 'node:path';
import { execFileSync } from 'node:child_process';
import * as NodeServices from '@effect/platform-node/NodeServices';
import * as NodeWS from '@effect/platform-node/NodeWS';
import { ORCHESTRATION_PROTOCOL_VERSION, WsRpcGroup } from '@t3tools/contracts';
import * as Effect from 'effect/Effect';
import * as Layer from 'effect/Layer';
import { RpcClient, RpcSerialization } from 'effect/rpc';
import { Socket } from 'effect/socket';

// Run from the tested checkout: node scripts/xlsx-proof.ts FIXTURES OUTPUT.
const [fixtures, output] = process.argv.slice(2);
const home = path.resolve('.t3');
const {origin} = JSON.parse(await fs.readFile(path.join(home,'userdata/server-runtime.json'),'utf8'));
const token = execFileSync(process.execPath,['apps/server/src/bin.ts','auth','session','issue','--base-dir',home,'--token-only'],{encoding:'utf8'}).trim();
const ticketResponse = await fetch(`${origin}/api/auth/websocket-ticket`,{method:'POST',headers:{authorization:`Bearer ${token}`}});
if(!ticketResponse.ok) throw new Error(`Ticket HTTP ${ticketResponse.status}`);
const {ticket} = await ticketResponse.json();
const sha = execFileSync('git',['rev-parse','HEAD'],{encoding:'utf8'}).trim();
const runDir = path.join(output,new Date().toISOString().replaceAll(':','-'));
await fs.mkdir(runDir,{recursive:true});
const rows: {name:string,status:number,text:string,sha256:string}[] = [];
await Effect.runPromise(Effect.scoped(Effect.gen(function*(){
 const protocol = yield* Layer.build(RpcClient.layerProtocolSocket().pipe(
  Layer.provide(Socket.layerWebSocket(`${origin.replace(/^http/,'ws')}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket)}`)),
  Layer.provide(RpcSerialization.layerJson),Layer.provide(NodeWS.layerWebSocketConstructor)));
 const rpc = yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol));
 for(const name of ['padded-id','general-neg-zero','dxf-override','control','dxf-collision']){
  const bytes = yield* Effect.promise(()=>fs.readFile(path.join(fixtures,`${name}.xlsx`)));
  const slot = yield* rpc['attachments.createUploadUrl']({type:'file',name:`${name}.xlsx`,mimeType:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',sizeBytes:bytes.length});
  const res = yield* Effect.promise(()=>fetch(`${origin}${slot.relativeUrl}`,{method:'POST',body:bytes}));
  if(res.status!==204) throw new Error(`Upload ${name}: HTTP ${res.status}: ${yield* Effect.promise(()=>res.text())}`);
  const text = yield* Effect.promise(()=>fs.readFile(path.join(home,'userdata/attachments',`${slot.attachmentId}.xlsx.txt`),'utf8'));
  const {createHash} = yield* Effect.promise(()=>import('node:crypto'));
  rows.push({name,status:res.status,text,sha256:createHash('sha256').update(bytes).digest('hex')});
  yield* Effect.promise(()=>fs.writeFile(path.join(runDir,`${name}.txt`),text));
 }
})).pipe(Effect.provide(NodeServices.layer)));
const report = [`T3 Code - real server XLSX upload extraction`,`Commit: ${sha}`,`Environment: Linux; fresh dev state; T3CODE_DEV_SEED=0`,`Transport: authenticated WebSocket upload slots, HTTP POST`,`Source: server-written .xlsx.txt sidecars (no parser called by driver)`, '',...rows.flatMap(r=>[`${r.name}.xlsx - HTTP ${r.status}`,r.text.trim(),''])].join('\n');
await fs.writeFile(path.join(runDir,'transcript.txt'),report);
await fs.writeFile(path.join(runDir,'results.json'),JSON.stringify({sha,rows},null,2));
console.log(report);
console.log(`Saved: ${runDir}`);
