import { DatabaseSync } from "node:sqlite";
import { readFile, writeFile } from "node:fs/promises";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

// Authentication belongs to the disposable factory test account, never to the evidence.
const authPath = process.env.GUEST_PROOF_AUTH_FILE!;
const relay = process.env.T3CODE_RELAY_URL!;
const kept = "a".repeat(254);

test("Guest attachment truncation keeps whole characters through approval", WEB,
  async ({ t3, app, browser, screen }) => {
    const captureName = async (label: string, name: string) => {
      await browser.evaluate(({ label, name }) => {
        const panel = document.createElement("aside");
        panel.id = "proof-dom-inspector";
        panel.style.cssText = "position:fixed;z-index:99999;left:288px;bottom:175px;width:640px;padding:16px;background:#111827;color:#f9fafb;border:2px solid #64748b;border-radius:8px;font:14px/1.5 monospace;white-space:pre-wrap;overflow-wrap:anywhere";
        panel.textContent = `READ-ONLY EVIDENCE INSPECTOR (not product UI)\n${label} — actual DOM filename:\n${name}\n\nUTF-16 units: ${name.length}  |  isWellFormed(): ${name.isWellFormed()}\nTrailing units: ${Array.from({ length: 3 }, (_, i) => "U+" + name.charCodeAt(name.length - 3 + i).toString(16).toUpperCase().padStart(4, "0")).join(" ")}`;
        document.body.append(panel);
        return null;
      }, { label, name });
      await app.screenshot(label);
      await browser.evaluate(() => { document.getElementById("proof-dom-inspector")!.remove(); return null; });
    };
    const project = await t3.project("guest-attachments");
    const thread = await t3.thread({ project, title: "Emoji filename test", messages: ["first"] });
    const { origin } = JSON.parse(await readFile(`${T3_HOME}/userdata/server-runtime.json`, "utf8"));
    const { accessToken } = JSON.parse(await readFile(authPath, "utf8"));
    const issued = await runPromise(makeState(T3_HOME).cli(["auth", "session", "issue", "--token-only", "--scope", "relay:configure", "--scope", "relay:write", "--scope", "relay:read"]));
    const localToken = issued.stdout.trim();
    const request = async (base: string, path: string, token: string, payload?: unknown, method = "POST") => {
      const response = await fetch(`${base}${path}`, { method, headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, ...(payload === undefined ? {} : { body: JSON.stringify(payload) }) });
      if (!response.ok) throw new Error(`${path}: ${response.status} ${await response.text()}`);
      return response.json();
    };
    await runPromise(Effect.gen(function* () {
      const client = yield* rpcClient(T3_HOME, origin);
      yield* client["cloud.installRelayClient"]({}).pipe(Stream.runDrain);
    }).pipe(Effect.scoped));
    const flags = { notificationsEnabled: false, liveActivitiesEnabled: false, managedTunnelsEnabled: true };
    const challenge = await request(relay, "/v1/client/environment-link-challenges", accessToken, flags);
    const proof = await request(origin, "/api/connect/link-proof", localToken, {
      challenge: challenge.challenge, relayIssuer: relay,
      endpoint: { httpBaseUrl: origin, wsBaseUrl: origin.replace(/^http/, "ws") + "/ws", providerKind: "cloudflare_tunnel" },
      origin: { localHttpHost: "127.0.0.1", localHttpPort: Number(new URL(origin).port) },
    });
    const link = await request(relay, "/v1/client/environment-links", accessToken, { proof, ...flags });
    try {
      await request(origin, "/api/connect/relay-config", localToken, {
        relayUrl: relay, relayIssuer: link.relayIssuer, cloudUserId: link.cloudUserId,
        environmentCredential: link.environmentCredential, cloudMintPublicKey: link.cloudMintPublicKey, endpointRuntime: link.endpointRuntime,
      });
      await t3.open("/settings/labs");
      await screen.getByRole("switch", "Guest links", { exact: true }).tap();
      await t3.open(thread);
      await screen.getByRole("button", "Thread actions for Emoji filename test").tap();
      await screen.getByRole("menuitem", "Share with guest", { exact: true }).tap();
      await screen.getByRole("button", "Create link", { exact: true }).tap();
      await screen.getByRole("textbox", "Guest link", { exact: true }).waitFor();
      const guestLink = await browser.evaluate(() => (document.querySelector('input[aria-label="Guest link"]') as HTMLInputElement).value);
      await screen.getByRole("button", "Done", { exact: true }).tap();
      const ownerCookies = await browser.cookies();
      await browser.clearCookies();
      // A clean cookie jar is the incognito guest; use the local route to the same server.
      await app.open(`/guest${new URL(guestLink).hash}`);
      await screen.getByRole("textbox", "Your name").fill("Guest Tester");
      await screen.getByRole("button", "Join", { exact: true }).tap();
      await screen.getByRole("textbox", "Message", { exact: true }).waitFor();
      await browser.evaluate(() => {
        const input = document.querySelector('input[type="file"]') as HTMLInputElement;
        const data = new DataTransfer();
        data.items.add(new File(["hello from guest"], "a".repeat(254) + "😀.txt", { type: "text/plain" }));
        input.files = data.files;
        input.dispatchEvent(new Event("change", { bubbles: true }));
        return null;
      });
      await screen.getByRole("textbox", "Message", { exact: true }).fill("Emoji filename test");
      await screen.getByRole("button", "Send", { exact: true }).tap();
      await screen.getByText("Waiting for approval", { exact: true }).waitFor();
      const guestName = await browser.evaluate(() => document.querySelector('a[download]')!.getAttribute("download")!);
      await browser.evaluate(() => { const el = document.querySelector('a[download] span.truncate')!; el.scrollLeft = el.scrollWidth; return null; });
      await captureName("guest-waiting-filename-end", guestName);
      await browser.clearCookies();
      await browser.setCookies(ownerCookies);
      await t3.open(thread);
      await screen.getByRole("list", "1 guest message waiting", { exact: true }).waitFor();
      const pendingName = await browser.evaluate(() => document.querySelector('button[aria-label^="Preview aaa"]')!.getAttribute("aria-label")!.slice(8));
      await browser.evaluate(() => { const el = document.querySelector('button[aria-label^="Preview aaa"] span.truncate')!; el.scrollLeft = el.scrollWidth; return null; });
      await captureName("owner-pending-filename-end", pendingName);
      await screen.getByRole("button", "Send message from Guest Tester", { exact: true }).tap();
      await screen.getByRole("list", "1 guest message waiting", { exact: true }).waitFor({ state: "hidden" });
      await screen.getByRole("button", /^Preview aaa/).waitFor();
      const sentName = await browser.evaluate(() => document.querySelector('button[aria-label^="Preview aaa"]')!.getAttribute("aria-label")!.slice(8));
      await browser.evaluate(() => { const el = document.querySelector('button[aria-label^="Preview aaa"] span.truncate'); if(el) el.scrollLeft = el.scrollWidth; return null; });
      await captureName("owner-approved-filename-end", sentName);
      const names = [guestName, pendingName, sentName];
      console.log("FILENAME OBSERVATIONS", JSON.stringify(names.map(name => ({ length: name.length, wellFormed: name.isWellFormed(), tail: Array.from({ length: 3 }, (_, i) => name.charCodeAt(name.length - 3 + i).toString(16)) }))));
      const db = new DatabaseSync(`${T3_HOME}/userdata/statev2.sqlite`, { readOnly: true });
      const events = db.prepare("SELECT sequence, event_type, payload_json FROM orchestration_events WHERE event_type IN ('thread.guest-share-updated', 'message.updated') ORDER BY sequence").all();
      db.close();
      const storedNames: Array<{ sequence: number; eventType: string; name: string }> = [];
      for (const event of events) {
        const visit = (value: unknown) => {
          if (!value || typeof value !== "object") return;
          if ("name" in value && "mimeType" in value && typeof value.name === "string") storedNames.push({ sequence: Number(event.sequence), eventType: String(event.event_type), name: value.name });
          for (const child of Object.values(value)) visit(child);
        };
        visit(JSON.parse(String(event.payload_json)));
      }
      const observations = { input: { name: kept + "😀.txt", content: "hello from guest", mimeType: "text/plain" }, dom: { guestWaiting: guestName, ownerPending: pendingName, ownerApproved: sentName }, storedNames };
      await writeFile(`${process.env.GUEST_PROOF_OUTPUT_DIR}/observations-${Date.now()}.json`, JSON.stringify(observations, null, 2));
      expect(names).toEqual([kept, kept, kept]);
    } finally {
      await request(origin, "/api/connect/unlink", localToken).catch(() => {});
      await request(relay, `/v1/client/environment-links/${link.environmentId}`, accessToken, undefined, "DELETE").catch(() => {});
    }
  });
