import { expect } from "e2e";
import { mkdir, writeFile } from "node:fs/promises";
import { test, WEB } from "./t3.ts";

// Real stage account and remote tunnel; only the OTLP receiver is a recording stand-in.
test("Relay attempt exports omit the host label while the app displays it", WEB, async ({ t3, app, screen, browser }) => {
  // Mask unrelated shared-account labels in recordings; keep the proof label visible.
  await browser.addInitScript(() => {
    document.addEventListener("DOMContentLoaded", () => {
      const style = document.createElement("style");
      style.textContent = 'p.truncate.text-sm.font-medium:not([data-proof-label]), span.block.truncate.text-sm.font-medium:not([data-proof-label]) { visibility: hidden !important; }';
      document.head.append(style);
      new MutationObserver(() => {
        document.querySelectorAll("p, span").forEach((element) => {
          if (element.textContent === "Relay Proof Laptop" && !element.hasAttribute("data-proof-label")) element.setAttribute("data-proof-label", "");
        });
      }).observe(document.body, { subtree: true, childList: true, characterData: true });
    });
  });
  const exports: unknown[] = [];
  let attemptCount = 0;
  let sawAttempt!: () => void;
  let nextAttempt = new Promise<void>((resolve) => { sawAttempt = resolve; });
  await browser.route("https://trace-proof.invalid/v1/traces", async (route) => {
    if (route.request.method === "POST") {
      const payload = JSON.parse(route.request.postData ?? "{}");
      exports.push(payload);
      const spans = payload.resourceSpans?.flatMap((r: any) => r.scopeSpans?.flatMap((s: any) => s.spans ?? []) ?? []) ?? [];
      attemptCount += spans.filter((s: any) => s.name === "relay.connection.attempt").length;
      if (attemptCount >= 2) sawAttempt();
    }
    await route.fulfill({ status: 202, headers: { "access-control-allow-origin": "*", "access-control-allow-headers": "*" }, body: "" });
  });
  await t3.project("Relay proof");
  await t3.open("/settings/connections");
  await screen.getByRole("button", "Sign in to T3 Connect", { exact: true }).first().tap();
  await browser.evaluate(async (credentials) => {
    const clerk = (window as any).Clerk;
    let result = await clerk.client.signIn.create({ identifier: credentials.email, password: credentials.password });
    if (result.status === "needs_second_factor") {
      await clerk.client.signIn.prepareSecondFactor({ strategy: "email_code" });
      result = await clerk.client.signIn.attemptSecondFactor({ strategy: "email_code", code: credentials.code });
    }
    if (result.status !== "complete") throw new Error(`Stage sign-in stopped at ${result.status}`);
    await clerk.setActive({ session: result.createdSessionId });
    clerk.closeSignIn();
  }, { email: process.env.FACTORY_USER_1_EMAIL, password: process.env.FACTORY_USER_1_PASSWORD, code: process.env.FACTORY_CLERK_EMAIL_CODE });
  await screen.getByRole("button", "Not now", { exact: true }).tap();
  await screen.getByRole("button", "Done", { exact: true }).tap();
  // Scope Add to the real remote's row, so other agents' shared test environments are untouched.
  await browser.locator('div').filter({ has: screen.getByText("Relay Proof Laptop", { exact: true }) }).filter({ has: screen.getByRole("button", "Add", { exact: true }) }).last().getByRole("button", "Add", { exact: true }).tap();
  await screen.getByText("T3 Connect · Connected", { exact: true }).waitFor({ timeout: 60_000 });
  await app.screenshot("connected-label");
  nextAttempt = new Promise<void>((resolve) => { sawAttempt = resolve; });
  await screen.getByRole("switch", "Switch off Relay Proof Laptop").tap();
  await screen.getByRole("switch", "Switch on Relay Proof Laptop").tap();
  await screen.getByText("T3 Connect · Connected", { exact: true }).waitFor({ timeout: 60_000 });
  await nextAttempt;
  const attempts = exports.flatMap((p: any) => p.resourceSpans?.flatMap((r: any) => r.scopeSpans?.flatMap((s: any) => (s.spans ?? []).filter((span: any) => span.name === "relay.connection.attempt").map((span: any) => ({ resource: r.resource, ...span }))) ?? []) ?? []);
  const folder = `${process.env.RELAY_PROOF_OUTPUT}/${Date.now()}`;
  await mkdir(folder, { recursive: true });
  await writeFile(`${folder}/attempts.json`, JSON.stringify(attempts, null, 2));
  await browser.evaluate((attempts) => {
    const panel = document.createElement("pre");
    panel.style.cssText = "position:fixed;z-index:999999;right:12px;bottom:12px;max-width:650px;max-height:470px;overflow:auto;background:#101820;color:#fff;padding:16px;border:2px solid #65c9ce;font:12px monospace;white-space:pre-wrap";
    panel.textContent = "OBSERVER: captured real OTLP relay.connection.attempt export\n" + JSON.stringify(attempts.map((s: any) => ({ name: s.name, attributes: Object.fromEntries((s.attributes ?? []).map((a: any) => [a.key, a.value.stringValue ?? a.value.intValue ?? a.value.boolValue])) })), null, 2);
    document.body.append(panel);
  }, attempts);
  await app.screenshot("relay-attempt-export");
  expect(attempts.length).toBeGreaterThan(1);
  expect(attempts.flatMap((s: any) => s.attributes ?? []).some((a: any) => a.key === "environment.label")).toBe(false);
});
