import { describe, expect, it, vi } from "vitest";
import { createAgentSdkStderrSink } from "../../src/agent/diagnostics.js";

describe("agent SDK stderr diagnostics", () => {
  it("redacts a credential split across chunks and correlates the log", () => {
    const warn = vi.fn();
    const sink = createAgentSdkStderrSink({
      logger: { warn },
      runId: "run-1",
      projectId: "project-1",
      sensitiveValues: ["provider-secret"],
    });

    sink.write("sandbox startup token=provider-");
    sink.write("secret\nremaining diagnostic");
    sink.flush();

    const serialized = JSON.stringify(warn.mock.calls);
    expect(serialized).not.toContain("provider-secret");
    expect(serialized).toContain("[REDACTED]");
    expect(warn).toHaveBeenCalledWith(
      expect.objectContaining({ runId: "run-1", projectId: "project-1" }),
      "agent SDK stderr",
    );
  });

  it("bounds line length, line count, and an unterminated line", () => {
    const warn = vi.fn();
    const sink = createAgentSdkStderrSink({
      logger: { warn },
      runId: "run-2",
      projectId: "project-2",
      sensitiveValues: [],
    });

    sink.write(`${"x".repeat(3_000)}\n`);
    sink.write(Array.from({ length: 30 }, (_, index) => `line-${index}`).join("\n"));
    sink.flush();

    expect(warn.mock.calls.length).toBeLessThanOrEqual(21);
    const diagnostics = warn.mock.calls
      .map(([bindings]) => (bindings as { sdkStderr?: string }).sdkStderr)
      .filter((value): value is string => value !== undefined);
    expect(diagnostics.every((value) => value.length <= 2_000)).toBe(true);
    expect(warn.mock.calls.some(([, message]) => String(message).includes("limit reached"))).toBe(true);
  });
});
