import { createServer } from "node:http";
import { execFileSync } from "node:child_process";
import { writeFileSync, mkdirSync } from "node:fs";
import { surfaceOf } from "@e2e-dev/web";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { stripeEngine } from "./usage-refill-engine.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

const analyze = String.raw`
import sys,json,io,statistics
from PIL import Image
im=Image.open(io.BytesIO(sys.stdin.buffer.read())).convert('RGB')
bars=json.loads(sys.argv[1]); results=[]
for b in bars:
 x,y,w,h=[round(b[k]*2) for k in ('x','y','width','height')]
 runs=[]
 for yy in list(range(y+6,y+14)):
  values=[sum(im.getpixel((xx,yy)))/3 for xx in range(x+10,x+w-10)]
  if not values: continue
  bg=min(values); parts=[]; start=None
  for i,v in enumerate(values+[bg]):
   if v>bg+8 and start is None: start=i
   if v<=bg+8 and start is not None:
    if start>0 and i<len(values) and not (b.get('markerX') is not None and x+10+i > b['markerX']*2-16 and x+10+start < (b['markerX']+b['markerWidth'])*2+16): parts.append({'width':i-start,'weight':round(sum(v-bg for v in values[start:i]),2)})
    start=None
  runs+=parts
 if not runs: continue
 med=statistics.median(r['weight'] for r in runs)
 thin=[r for r in runs if r['weight']<med*.8]
 results.append({'label':b['label'],'count':len(runs),'thin':len(thin),'thinFraction':len(thin)/len(runs),'medianWeight':med,'widths':{str(k):sum(r['width']==k for r in runs) for k in sorted(set(r['width'] for r in runs))}})
print(json.dumps(results))
`;

test("Interior usage refill stripes have consistent visual weight", WEB, async ({t3, app, browser, screen}) => {
  const now = Date.now();
  const reset = (hours:number) => new Date(now+hours*3600000).toISOString();
  const files = ['codex','claude'].flatMap(provider => ['a','b'].map(id=>({id:`${provider}-${id}`,auth_index:`${provider}-${id}`,provider,email:`account-${id}@example.invalid`,id_token:{plan_type:'pro',chatgpt_account_id:`synthetic-${id}`}})));
  const hub = createServer(async(req,res)=>{
    res.setHeader('content-type','application/json');
    if(req.url?.endsWith('/auth-files')) return res.end(JSON.stringify({files}));
    let raw=''; for await(const chunk of req) raw+=chunk;
    const request=JSON.parse(raw||'{}');
    const b=request.auth_index?.endsWith('-b');
    const body=request.url?.includes('reset-credits') ? {credits:[]} : request.auth_index?.startsWith('codex') ? {
      plan_type:'pro',rate_limit:{primary_window:{used_percent:b?45:72,reset_at:Math.floor((now+2*3600000)/1000),limit_window_seconds:18000},secondary_window:{used_percent:b?48:83,reset_at:Math.floor((now+72*3600000)/1000),limit_window_seconds:604800}}
    } : {five_hour:{utilization:b?55:78,resets_at:reset(3)},seven_day:{utilization:b?47:81,resets_at:reset(96)},limits:[{kind:'weekly_scoped',percent:b?62:88,resets_at:reset(96),scope:{model:{display_name:'Fable'}}}]};
    res.end(JSON.stringify({status_code:200,body:JSON.stringify(body)}));
  });
  await new Promise<void>(resolve=>hub.listen(0,'127.0.0.1',resolve));
  try {
    await t3.project('Usage stripe demo');
    await runPromise(Effect.gen(function*(){
      const client=yield* rpcClient(T3_HOME,app.baseUrl??'');
      yield* client['server.updateSettings']({patch:{usageLimitSources:{synthetic:{kind:'cliproxy',label:'Synthetic usage accounts',url:`http://127.0.0.1:${(hub.address() as {port:number}).port}`,managementKey:'synthetic-fixture-key',enabled:true}}}});
    }).pipe(Effect.scoped));
    await browser.emulateMedia({colorScheme:'dark'});
    await browser.addInitScript(()=>{localStorage.setItem('t3code:theme','dark');localStorage.setItem('t3code:usage-page-preferences:v1',JSON.stringify({metric:'limits',windowDays:30}));});
    await t3.open('/usage');
    const live=surfaceOf(stripeEngine)!;
    const page=live.page();
    await screen.getByRole('button','Refresh limits',{exact:true}).tap();
    await page.locator('[style*="repeating-linear-gradient"]').nth(9).waitFor({state:'visible'});
    await page.mouse.move(1,1);
    // Static rendering proof: keep the first stable pair, 500 ms apart.
    let previous=await page.screenshot();
    for(let n=0;n<10;n++){
      await new Promise(resolve=>setTimeout(resolve,500));
      const current=await page.screenshot();
      if(current.equals(previous)) break;
      previous=current;
      if(n===9) throw new Error('Usage screenshot did not settle');
    }
    console.log('CAPTURE_ENVIRONMENT',await browser.evaluate(()=>({userAgent:navigator.userAgent,dpr:devicePixelRatio,width:innerWidth,height:innerHeight,theme:document.documentElement.className})));
    await app.screenshot('usage-limits-dpr2');
    const geometry=await page.locator('[style*="repeating-linear-gradient"]').evaluateAll(elements=>elements.map(e=>{const b=e.getBoundingClientRect();const button=e.closest('button');const marker=button?.querySelector(':scope > span[aria-hidden][style]')?.getBoundingClientRect();return {x:b.x,y:b.y,width:b.width,height:b.height,label:button?.getAttribute('aria-label'),markerX:marker?.x,markerWidth:marker?.width};}));
    const png=await page.screenshot();
    const result=JSON.parse(execFileSync('python3',['-c',analyze,JSON.stringify(geometry)],{input:png}).toString());
    console.log('STRIPE_MEASUREMENTS',JSON.stringify(result));
    const output=(process.env.T3_STRIPE_ARTIFACTS ?? '/tmp/usage-refill-proof')+'/'+Date.now();
    mkdirSync(output,{recursive:true});
    writeFileSync(output+'/usage.png',png);
    writeFileSync(output+'/geometry.json',JSON.stringify(geometry));
    writeFileSync(output+'/measurements.json',JSON.stringify(result,null,2));
    const worst=Math.max(...result.filter((r:{count:number})=>r.count>80).map((r:{thinFraction:number})=>r.thinFraction));
    expect(worst).toBeLessThan(0.03);
  } finally {
    await new Promise<void>((resolve,reject)=>hub.close(e=>e?reject(e):resolve()));
  }
});
