import { readFile } from "node:fs/promises";
import { setTimeout } from "node:timers/promises";
import { createServer } from "node:http";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Custom endpoint usage popup offers separately labelled hub limits", WEB, async ({t3, app, screen, browser}) => {
  const capture = async (label: string) => {
    let previous = await readFile(await app.screenshot(label+'-settling'));
    for (let attempt=0;attempt<8;attempt++) {
      await setTimeout(500);
      const current=await readFile(await app.screenshot(label));
      if(previous.equals(current)) return;
      previous=current;
    }
    throw new Error('Capture did not settle: '+label);
  };
  const hub = createServer(async (req,res) => {
    res.setHeader('Content-Type','application/json');
    if (req.url?.endsWith('/auth-files')) res.end(JSON.stringify({files:[{id:'demo.json',auth_index:'demo',provider:'claude',email:'demo@example.invalid'}]}));
    else res.end(JSON.stringify({status_code:200,body:JSON.stringify({five_hour:{utilization:25,resets_at:new Date(Date.now()+2*60*60*1000).toISOString()},seven_day:{utilization:40,resets_at:new Date(Date.now()+5*24*60*60*1000).toISOString()}})}));
  });
  await new Promise<void>(resolve=>hub.listen(0,'127.0.0.1',resolve));
  const endpoint = `http://127.0.0.1:${(hub.address() as {port:number}).port}`;
  try {
    const project=await t3.project('Hub usage demo');
    await t3.thread({project,title:'Hub quota example',messages:['Ready for work']});
    await browser.setViewport({width:1100,height:800});
    await t3.open();
    await screen.getByRole('button',/^Hub quota example,/).tap();
    await browser.evaluate(async (endpoint)=>{
      const {appAtomRegistry:r}=await import('/src/rpc/atomRegistry.ts');
      const {primaryEnvironmentIdAtom}=await import('/src/state/primaryEnvironment.ts');
      const {serverEnvironment:s}=await import('/src/state/server.ts');
      const environmentId=r.get(primaryEnvironmentIdAtom);
      const result=await s.updateSettings.run(r,{environmentId,input:{patch:{providerInstances:{...r.get(s.settingsValueAtom(environmentId)).providerInstances,hubClaude:{driver:'claudeAgent',displayName:'Custom endpoint',enabled:true,config:{customModels:[{slug:'demo-model',name:'Demo model'}]},environment:[{name:'ANTHROPIC_BASE_URL',value:endpoint,sensitive:false}]}},usageLimitSources:{demoHub:{kind:'cliproxy',label:'Demo hub',url:endpoint,managementKey:'synthetic-key',enabled:true}}}}});
      const {updateClientSettings}=await import('/src/hooks/useSettings.ts');
      updateClientSettings({threadDetailsItems:{usage:true},theme:'dark'});
      const {environmentShell}=await import('/src/state/shell.ts');
      const state=r.get(environmentShell.stateValueAtom(environmentId));
      const threadId=state.snapshot.value.threads[0].id;
      const {orchestrationEnvironment}=await import('/src/state/orchestration.ts');
      const changed=await orchestrationEnvironment.v2.dispatchCommand.run(r,{environmentId,input:{type:'thread.model-selection.set',commandId:crypto.randomUUID(),threadId,modelSelection:{instanceId:'hubClaude',model:'demo-model'}}});
      if(changed._tag!=='Success'||result._tag!=='Success') throw new Error('Fixture RPC failed');
      const refreshed=await s.refreshProviders.run(r,{environmentId,input:{instanceId:'hubClaude',cwd:state.snapshot.value.projects[0].workspaceRoot,fresh:true}});
      if(refreshed._tag!=='Success') throw new Error('Provider refresh failed');
      return null;
    },endpoint);
    await app.open('/usage');
    await screen.getByText('75%',{exact:true}).first().waitFor({state:'visible'});
    await capture('hub-quotas');
    await screen.getByRole('button','Close',{exact:true}).tap();
    await screen.getByRole('button',/^Hub quota example,/).tap();
    const composer=screen.getByRole('textbox');
    await composer.fill('/usage-limits');
    await composer.press('Enter');
    await screen.getByRole('button','Dismiss usage limits').waitFor({state:'visible'});
    await capture('slash-usage-report');
    await screen.getByRole('button','Dismiss usage limits').tap();
    await screen.getByRole('button','Toggle thread details panel').tap();
    await screen.getByRole('region','Usage limits').waitFor({state:'visible'});
    await capture('usage-popup');
    
    await expect(screen.getByRole('button','View hub limits')).toBeVisible();
    await screen.getByRole('button','View hub limits').tap();
    await expect(screen.getByRole('button','Dismiss usage limits')).toBeVisible();
    await capture('opened-hub-report');
  } finally {hub.closeAllConnections(); await new Promise<void>(resolve=>hub.close(()=>resolve()));}
});
