import {
  assertDocMatch,
  initDocFile,
  collectAllCommands,
  type GenerateDocConfig,
  type FileMapping,
} from "politty/docs";
import { describe, test, beforeAll } from "vitest";
import { mainCommand } from "./commands/index";

function capitalize(s: string): string {
  return s.charAt(0).toUpperCase() + s.slice(1);
}

async function buildFilesFromCommand(): Promise<FileMapping> {
  const allCommands = await collectAllCommands(mainCommand);
  const files: FileMapping = {};

  // Single-file full reference
  files["docs/cli.md"] = { commands: [""], title: "CLI Reference" };

  // Per-command sub-files
  for (const [path, info] of allCommands) {
    if (info.depth !== 2) continue;

    const title =
      info.subCommands.length > 0 ? `${capitalize(path)} Commands` : `${capitalize(path)} Command`;

    files[`docs/cli/${path}.md`] = { commands: [path], title };
  }

  return files;
}

const files = await buildFilesFromCommand();
const targetCommands = Object.values(files).flatMap((f) =>
  typeof f === "object" && "commands" in f ? f.commands : f,
);

const config: GenerateDocConfig = {
  command: mainCommand,
  files,
  format: {
    headingLevel: 2,
    optionStyle: "table",
    generateAnchors: true,
    includeSubcommandDetails: true,
  },
};

describe("CLI documentation", () => {
  beforeAll(() => {
    initDocFile(config);
  });

  for (const cmd of targetCommands) {
    test(cmd || "root", async () => {
      await assertDocMatch({ ...config, targetCommands: [cmd] });
    });
  }

  test("all", async () => {
    await assertDocMatch(config);
  });
});
