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

// The app normally persists these first-page answers after a forge read. Seed one synthetic
// cached row so author filtering runs without a signed-in forge or any real repository data.
test("Bare numeric author and labels URLs keep the Pull Requests page renderable", WEB, async ({ t3, app, browser, screen }) => {
  // Synthetic external CLI replies; server, WebSocket, router, cache, and UI remain real.
  const fixture = `#!/usr/bin/env python3
import json, sys
args = sys.argv[1:]
repo = {"full_name": "example/filter-demo", "permissions": {"push": False, "admin": False}}
pr = {"number": 1, "title": "Synthetic filter demonstration", "body": "Synthetic evidence data",
      "html_url": "https://codeberg.org/example/filter-demo/pulls/1", "user": {"login": "demo-author"},
      "state": "open", "merged": False, "mergeable": True,
      "head": {"ref": "demo", "sha": "a" * 40, "repo": repo},
      "base": {"ref": "main", "sha": "b" * 40, "repo": repo},
      "created_at": "2026-11-01T00:00:00Z", "updated_at": "2026-11-01T00:00:00Z",
      "closed_at": None, "merged_at": None, "additions": 1, "deletions": 0, "labels": []}
if len(args) > 1 and args[0] == "login" and args[1] in ["list", "status"]:
    print(json.dumps([{"name": "demo", "url": "https://codeberg.org", "user": "demo-author", "default": "true", "valid": "true"}]))
elif args and args[0] == "api":
    path = args[-1].split("/api/v1/")[-1].split("?")[0]
    print("HTTP/1.1 200 OK", file=sys.stderr)
    if path == "user": result = {"login": "demo-author"}
    elif path.endswith("/pulls"): result = [pr] if "state=closed" not in args[-1] else []
    elif path.endswith("/pulls/1"): result = pr
    elif path == "repos/example/filter-demo": result = repo
    else: result = []
    print(json.dumps(result))
else:
    print("tea version 0.16.0")
`;
  await writeFile(`${T3_HOME}/bin/tea`, fixture);
  await chmod(`${T3_HOME}/bin/tea`, 0o755);
  await t3.project("Filter demo", { ".git/config": '[remote "origin"]\n  url = https://codeberg.org/example/filter-demo.git\n  fetch = +refs/heads/*:refs/remotes/origin/*\n' });
  await t3.open();
  await screen.getByText("Filter demo", { exact: true }).first().waitFor({ state: "visible" });
  const seed = async () => browser.evaluate(async () => {
    const { readProjects } = await import("/src/state/entities.ts");
    const project = readProjects().find((p) => p.title === "Filter demo");
    if (!project) throw new Error("Synthetic project has not loaded");
    const entry = {
      provider: "forgejo", host: "codeberg.org", projectId: project.id, projectTitle: "Filter demo",
      repository: "example/filter-demo", number: 1, title: "Synthetic filter demonstration",
      url: "https://codeberg.org/example/filter-demo/pulls/1",
      author: { login: "demo-author", name: null, avatarUrl: null },
      headBranch: "demo", baseBranch: "main", state: "open", isDraft: false,
      mergeability: "mergeable", additions: 1, deletions: 0,
      createdAt: "2026-11-01T00:00:00Z", updatedAt: "2026-11-01T00:00:00Z",
      viewerReviewRequested: false, labels: [],
    };
    const answer = { entries: [entry], viewers: { "codeberg.org": "demo-author" },
      providers: [{ host: "codeberg.org", kind: "forgejo", searchesOnHost: false,
        projectCount: 1, configured: true, detail: null }], errors: [], truncated: false, nextCursors: {} };
    for (const involvement of ["all", "authored", "reviewing"]) {
      for (const filters of [undefined, { author: 4089 }]) {
        const key = "t3.pullRequests.listScope:" + JSON.stringify({ state: "open", involvement, limit: 99, ...(filters ? { filters } : {}) });
        localStorage.setItem(key, JSON.stringify({ [project.environmentId]: answer }));
      }
    }
  });
  await seed();
  await app.open("/pull-requests?author=4089");
  await screen.getByText("Something went wrong.", { exact: true }).or(screen.getByRole("heading", "Pull requests", { exact: true })).waitFor({ state: "visible" });
  await screen.getByText("Something went wrong.", { exact: true }).or(screen.getByText("Synthetic filter demonstration", { exact: true })).waitFor({ state: "visible" });
  await expect.soft(screen.getByText("Something went wrong.", { exact: true })).toBeHidden();
  await browser.evaluate(() => {
    const report = document.querySelector("pre");
    if (report && document.body.textContent?.includes("Something went wrong.")) {
      report.textContent = report.textContent?.replace(/\(http[^)]+\)/g, "(local source path redacted)") ?? "";
    }
  });
  await app.screenshot("numeric-author");
  // A full navigation resets the error boundary before checking the independent labels input.
  await app.open("/pull-requests?labels=4089");
  await screen.getByText("Something went wrong.", { exact: true }).or(screen.getByRole("heading", "Pull requests", { exact: true })).waitFor({ state: "visible" });
  await screen.getByText("Something went wrong.", { exact: true }).or(screen.getByText("Synthetic filter demonstration", { exact: true })).waitFor({ state: "visible" });
  await expect.soft(screen.getByText("Something went wrong.", { exact: true })).toBeHidden();
  await screen.getByText("Something went wrong.", { exact: true }).or(screen.getByText("Synthetic filter demonstration", { exact: true })).waitFor({ state: "visible" });
  await app.screenshot("numeric-labels");
});
