import { expect } from "e2e";
import * as fs from "node:fs/promises";
import * as path from "node:path";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("Usage discovery never downloads an uninstalled mise lazy tool", WEB, async ({t3, app, browser, screen}) => {
  await t3.project("usage-reproduction");
  const fixture = path.join(T3_HOME, "mise-fixture");
  await fs.mkdir(path.join(fixture, "invocation-downloads"), {recursive:true});
  const shim = `#!/usr/bin/python3
import os, sys, json, time, tempfile
root = ${JSON.stringify(fixture)}
with open(root + '/invocations.jsonl', 'a') as log:
    log.write(json.dumps({'argv':sys.argv[1:], 'MISE_OFFLINE':os.environ.get('MISE_OFFLINE', 'unset')}) + '\\n')
if os.environ.get('MISE_OFFLINE') == '1':
    sys.exit(1)
if len(sys.argv) < 2 or sys.argv[1] != 'serve':
    sys.exit(1)
directory = tempfile.mkdtemp(prefix='.tmp', dir=root + '/invocation-downloads')
with open(directory + '/partial', 'wb', buffering=0) as download:
    while True:
        download.write(b'x' * 1048576)
        time.sleep(1)
`;
  await fs.writeFile(path.join(T3_HOME, "bin/muse"), shim, {mode:0o755});
  const sample = async (stage:string) => {
    const lines = (await fs.readFile(path.join(fixture,"invocations.jsonl"),"utf8").catch(()=>"")).trim().split("\n").filter(Boolean).map(line=>JSON.parse(line));
    const dirs = await fs.readdir(path.join(fixture,"invocation-downloads"));
    let bytes = 0;
    for(const dir of dirs) bytes += (await fs.stat(path.join(fixture,"invocation-downloads",dir,"partial")).catch(()=>({size:0}))).size;
    const serves = lines.filter(line=>line.argv[0]==="serve");
    const diagnostic = {stage, sdkStarts:serves.length, offline:serves.map(line=>line.MISE_OFFLINE), partialDirectories:dirs.length, partialMiB:bytes/1048576};
    await browser.evaluate((data) => {
      let panel=document.getElementById("mise-evidence");
      if(!panel){panel=document.createElement("pre");panel.id="mise-evidence";document.body.append(panel);}
      panel.style.cssText="position:fixed;bottom:20px;right:20px;z-index:99999;background:#101827;color:#fff;border:2px solid #899ab5;padding:18px;font:16px/1.5 monospace;max-width:620px;white-space:pre-wrap";
      panel.textContent="TEST INSTRUMENTATION — mise lazy-tool stand-in\n"+JSON.stringify(data,null,2)+"\nObserved from real server child invocations and disk files.\nNo real Muse installation or account used.";
      return null;
    }, diagnostic);
    return diagnostic;
  };
  const observe = async (stage:string, seconds:number) => {
    let result;
    for(let i=0;i<seconds;i++) {await new Promise(resolve=>setTimeout(resolve,1000));result=await sample(stage);}
    return result!;
  };
  await t3.open("/usage");
  await observe("First Usage scan (22 seconds)",22);
  await app.screenshot("first-usage-scan");
  await app.open("/");
  await observe("Wait beyond 30-second failure cache",35);
  await app.open("/usage");
  const result = await observe("Reopen Usage after failure cache expires (22 seconds)",22);
  await app.screenshot("repeated-usage-scan");
  await fs.writeFile(path.join(fixture,"observations.json"),JSON.stringify(result,null,2));
  expect(result.sdkStarts).toBeGreaterThanOrEqual(2);
  expect(result.partialDirectories).toBe(0);
});
