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

test("Custom OpenCode reasoning can return to Default", WEB, async ({t3, app, screen, browser}) => {
  const capture = async (label: string) => {
    await new Promise(r => setTimeout(r, 700));
    for (let attempt = 0; attempt < 5; attempt++) {
      const first = await app.screenshot(label + '-stability');
      await new Promise(r => setTimeout(r, 500));
      const second = await app.screenshot(label);
      if ((await fs.readFile(first)).equals(await fs.readFile(second))) return;
    }
    throw new Error('Capture did not stabilize: ' + label);
  };
  const requests: any[] = [];
  const gateway = http.createServer(async (req,res) => {
    let raw = ""; for await (const c of req) raw += c;
    if (!raw) {res.writeHead(200, {'content-type':'application/json'}); res.end('{}'); return;}
    const body = JSON.parse(raw); requests.push(body);
    if (body.reasoning_effort) {res.writeHead(400, {'content-type':'application/json'}); res.end(JSON.stringify({error:{message:'Gateway rejects reasoning_effort; choose Default to omit it',type:'invalid_request_error'}})); return;}
    const text = 'Gateway accepted request without reasoning_effort.';
    if (body.stream) {
      res.writeHead(200, {'content-type':'text/event-stream'});
      for (const chunk of [{delta:{role:'assistant',content:text},finish_reason:null},{delta:{},finish_reason:'stop'}]) res.write('data: '+JSON.stringify({id:'chatcmpl-proof',object:'chat.completion.chunk',created:1,model:'proof-model',choices:[{index:0,...chunk}]})+'\n\n');
      res.end('data: [DONE]\n\n');
    } else {res.writeHead(200, {'content-type':'application/json'}); res.end(JSON.stringify({id:'chatcmpl-proof',object:'chat.completion',created:1,model:'proof-model',choices:[{index:0,message:{role:'assistant',content:text},finish_reason:'stop'}],usage:{prompt_tokens:1,completion_tokens:1,total_tokens:2}}));}
  });
  await new Promise<void>(r=>gateway.listen(0,'127.0.0.1',r));
  const port = (gateway.address() as any).port;
  const config = { $schema:'https://opencode.ai/config.json', enabled_providers:['proof-gateway'], provider:{'proof-gateway':{npm:'@ai-sdk/openai-compatible',name:'Proof Gateway',options:{baseURL:`http://127.0.0.1:${port}/v1`,apiKey:'synthetic'},models:{'proof-model':{name:'Gateway Custom Model',limit:{context:32000,output:2048},variants:{low:{reasoningEffort:'low'},medium:{reasoningEffort:'medium'},high:{reasoningEffort:'high'}}}}}}};
  const oc = spawn('opencode',['serve','--pure','--port','0','--hostname','127.0.0.1'],{env:{PATH:process.env.PATH,HOME:T3_HOME,OPENCODE_CONFIG_CONTENT:JSON.stringify(config),XDG_CONFIG_HOME:T3_HOME+'/oc-config',XDG_DATA_HOME:T3_HOME+'/oc-data',XDG_CACHE_HOME:T3_HOME+'/oc-cache'},stdio:['ignore','pipe','pipe']});
  try {
    let output='';
    const url = await new Promise<string>((resolve,reject)=>{const timer=setTimeout(()=>reject(new Error('OpenCode startup: '+output)),60000);oc.stdout.on('data',c=>{output+=c;const m=output.match(/http:\/\/127\.0\.0\.1:\d+/);if(m){clearTimeout(timer);resolve(m[0]);}});oc.stderr.on('data',c=>output+=c);});
    const settingsPath=T3_HOME+'/userdata/settings.json';
    const settings=JSON.parse(await fs.readFile(settingsPath,'utf8'));
    settings.providerInstances.opencode={driver:'opencode',enabled:true,config:{serverUrl:url}};
    await fs.writeFile(settingsPath,JSON.stringify(settings));
    const project=await t3.project('Gateway reasoning proof');
    const {cli}=makeState(T3_HOME);
    let started='';
    await expect.poll(async()=>{const r=await runPromise(cli(['thread','start',project,'Reply with a short acknowledgement.','--title','Custom reasoning reset','--provider','opencode','--model','proof-gateway/proof-model','--json'],[0,1]));if(r.stdout.includes('threadId'))started=r.stdout;return !!started;},{timeout:60000}).toBe(true);
    await t3.open({threadId:JSON.parse(started).threadId});
    await expect(screen.getByText('Gateway accepted request without reasoning_effort.').first()).toBeVisible({timeout:60000});
    const picker=browser.locator('[data-chat-provider-model-picker-label]').first();
    await picker.tap();
    await capture('untouched-reasoning');
    await screen.getByRole('radio','Low',{exact:true}).tap();
    await browser.keyboard.press('Escape');
    await screen.getByRole('textbox').fill('Try the explicitly selected low reasoning level.');
    await screen.getByRole('textbox').press('Enter');
    await expect(screen.getByText('Gateway rejects reasoning_effort; choose Default to omit it',{exact:false}).first()).toBeVisible({timeout:60000});
    await picker.tap();
    await capture('reset-choice');
    await expect(screen.getByRole('radio','Default',{exact:true})).toBeVisible();
    await screen.getByRole('radio','Default',{exact:true}).tap();
    await browser.keyboard.press('Escape');
    await screen.getByRole('textbox').fill('Retry with Default reasoning.');
    await screen.getByRole('textbox').press('Enter');
    await expect.poll(()=>requests.filter(r=>!r.reasoning_effort).length,{timeout:60000}).toBeGreaterThan(1);
    await expect(screen.getByRole('button','Stop generation')).toBeHidden({timeout:60000});
    await expect(screen.getByText('Gateway accepted request without reasoning_effort.').nth(1)).toBeVisible({timeout:60000});
    await capture('default-restored');
  } finally {oc.kill('SIGTERM'); gateway.closeAllConnections();gateway.close();}
});
