import { describe, expect, test } from "bun:test";
import { spawnSync } from "node:child_process";
import { rootPath } from "./config";
import { isRenderedCliResult } from "./output";
import { runPlatformObservabilityCommand } from "./platform-infra-observability";
import { renderObservabilityPlanFailure } from "./platform-infra-observability/plan-render";

describe("platform-infra observability progressive disclosure", () => {
  test("default plan is a bounded table while full and raw preserve the complete plan", async () => {
    const compact = await runPlatformObservabilityCommand({} as never, ["plan", "--target", "NC01"]);
    expect(isRenderedCliResult(compact)).toBe(true);
    if (!isRenderedCliResult(compact)) throw new Error("expected rendered plan");
    expect(Buffer.byteLength(compact.renderedText, "utf8")).toBeLessThan(10_240);
    expect(compact.renderedText).toContain("serviceConnections=8");
    expect(compact.renderedText).toContain("configRefs=6/6 missing=0");
    expect(compact.renderedText).toContain("--full");
    expect(compact.renderedText).toContain("--raw");

    for (const mode of ["--full", "--raw"]) {
      const expanded = await runPlatformObservabilityCommand({} as never, ["plan", "--target", "NC01", mode]);
      expect(isRenderedCliResult(expanded)).toBe(false);
      expect(expanded).toMatchObject({
        action: "platform-infra-observability-plan",
        mutation: false,
        renderPlan: { target: { id: "NC01", route: "NC01:k3s", namespace: "platform-infra" } },
      });
      expect((expanded as Record<string, any>).renderPlan.instrumentation).toHaveLength(8);
    }
  });

  test("real outer CLI keeps plan below the stdout dump threshold", () => {
    const result = cli(["platform-infra", "observability", "plan", "--target", "NC01"]);
    expect(result.status).toBe(0);
    expect(Buffer.byteLength(result.stdout, "utf8")).toBeLessThan(10_240);
    expect(result.stdout).toContain("platform-infra observability plan (ok)");
    expect(result.stdout).toContain("configRefs=6/6 missing=0");
    expect(result.stdout).not.toContain("outputTruncated");
    expect(result.stdout).not.toContain("/tmp/unidesk-cli-output");
  });

  test("search, trace and diagnose-code-agent expose only scoped help", () => {
    for (const operation of ["search", "trace", "diagnose-code-agent"]) {
      const result = cli(["platform-infra", "observability", operation, "--help"]);
      expect(result.status).toBe(0);
      const payload = JSON.parse(result.stdout) as Record<string, any>;
      expect(payload.data.scope).toBe(operation);
      expect(payload.data.command).toBe(`platform-infra observability ${operation}`);
      expect(payload.data.usage.every((line: string) => line.includes(`observability ${operation}`))).toBe(true);
      expect(result.stdout).not.toContain("platform-infra sub2api");
      expect(result.stdout).not.toContain("platform-infra langbot");
      expect(result.stdout).not.toContain("outputTruncated");
    }
  });

  test("top observability help is only an operation index", () => {
    const result = cli(["platform-infra", "observability", "--help"]);
    expect(result.status).toBe(0);
    const payload = JSON.parse(result.stdout) as Record<string, any>;
    expect(payload.data.operations.map((item: Record<string, unknown>) => item.name)).toEqual([
      "plan", "apply", "status", "validate", "trace", "search", "diagnose-code-agent",
    ]);
    expect(payload.data.scopedHelp).toContain("<operation> --help");
    expect(payload.data.usage).toBeUndefined();
    expect(result.stdout).not.toContain("platform-infra sub2api");
  });

  test("configRef failures name the source and a bounded next command", () => {
    const rendered = renderObservabilityPlanFailure(
      new Error("config/hwlab-node-lanes.yaml#lanes.v03.targets.NC01.runtime.namespace is missing segment namespace"),
      "NC01",
    );
    expect(rendered.ok).toBe(false);
    expect(rendered.renderedText).toContain("config/hwlab-node-lanes.yaml#lanes.v03.targets.NC01.runtime.namespace");
    expect(rendered.renderedText).toContain("rg -n lanes config/hwlab-node-lanes.yaml");
    expect(rendered.renderedText).not.toContain("/tmp/unidesk-cli-output");
  });
});

function cli(args: string[]): { status: number | null; stdout: string; stderr: string } {
  const result = spawnSync("bun", ["scripts/cli.ts", ...args], {
    cwd: rootPath(),
    encoding: "utf8",
    timeout: 30_000,
    env: { ...process.env, NO_COLOR: "1" },
  });
  expect(result.stdout).not.toBe("");
  return { status: result.status, stdout: result.stdout, stderr: result.stderr };
}
