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

// The real Pi version check succeeds; RPC startup fails to produce the reported catalog gap.
// No model is called. The outgoing request records what the real composer submits.
test("Pi retains an explicit model and thinking during failed discovery", WEB, async ({t3, app, browser, screen}) => {
  await browser.emulateMedia({colorScheme: "dark"});
  const screenshot = async (label: string) => {
    await browser.evaluate(() => {
      for (const animation of document.getAnimations()) {
        if (Number.isFinite(animation.effect?.getComputedTiming().endTime)) animation.finish();
      }
      return null;
    });
    await app.screenshot(label);
  };
  await browser.addInitScript(() => {
    (window as any).submittedSelections = [];
    const send = WebSocket.prototype.send;
    WebSocket.prototype.send = function(data) {
      if (typeof data === "string") {
        for (const message of [JSON.parse(data)].flat()) {
          if (message?._tag === "Request" && (message.tag === "orchestration.dispatchCommand" || message.tag === "orchestration.launchThread")) {
            if (message.payload?.modelSelection) (window as any).submittedSelections.push({method: message.tag, modelSelection: message.payload.modelSelection});
          }
        }
      }
      return send.call(this, data);
    };
  });
  const shim = path.join(T3_HOME, "bin", "pi-gap");
  await fs.writeFile(shim, '#!/bin/sh\nif [ "$1" = "--version" ]; then exec /usr/local/bin/pi --version; fi\necho "Intentional discovery outage for catalog-gap reproduction" >&2\nexit 1\n', {mode: 0o755});
  const settingsPath = path.join(T3_HOME, "userdata/settings.json");
  const settings = JSON.parse(await fs.readFile(settingsPath, "utf8"));
  settings.providerInstances.pi = {driver: "pi", enabled: true, config: {binaryPath: shim}};
  settings.defaultModelSelection = {instanceId: "pi", model: "anthropic/claude-sonnet-4", options: [{id: "thinking", value: "high"}]};
  await fs.writeFile(settingsPath, JSON.stringify(settings));
  await t3.project("Catalog gap demo");
  await t3.open();
  await screen.getByRole("textbox").fill("Keep my saved model and high thinking.");
  await browser.locator('[data-chat-provider-model-picker="true"]').tap();
  await screenshot("model-picker-during-gap");
  const pickerText = await browser.evaluate(() => document.body.innerText);
  await browser.keyboard.press("Escape");
  await screen.getByRole("textbox").press("Enter");
  // Wait for navigation after the composer creates and submits the thread.
  await screen.getByRole("textbox").fill("Inspecting the submitted selection");
  await screen.getByRole("button", "Submit message", {exact: true}).hover();
  await browser.locator('[data-chat-provider-model-picker="true"]').tap();
  await screenshot("model-picker-after-submit");
  const submitted = await browser.evaluate(() => (window as any).submittedSelections);
  console.log("SUBMITTED_SELECTIONS", JSON.stringify(submitted));
  await fs.writeFile(path.join(T3_HOME, "submitted-selection.json"), JSON.stringify({savedDefault: settings.defaultModelSelection, submitted}, null, 2));
  expect(pickerText).toContain("Unavailable");
  expect(JSON.stringify(submitted)).toContain('"model":"anthropic/claude-sonnet-4"');
  expect(JSON.stringify(submitted)).toContain('"id":"thinking","value":"high"');
});
