import type { CommandModule } from "yargs"
import { generateHelp, generateCommandTable } from "./help"
import { commands } from "./commands"
import { DevAliasCommand, DevSetupCommand } from "./cli/dev-setup"
import path from "path"

const root = path.resolve(import.meta.dir, "../../../..") + "/"

const TABLE_PATH = root + "packages/saeeol-docs/markdoc/partials/cli-commands-table.md"
const REFERENCE_PATH = root + "packages/saeeol-docs/pages/code-with-ai/platforms/cli-reference.md"

// End-user docs describe the release CLI. dev-setup / dev-alias are hidden
// from release builds (see InstallationBuildKind in commands.ts), so strip
// them here as well to keep saeeol.ai/docs in sync with the shipped binary.
// Cast mirrors loadCommands() in help.ts — the barrel's union type doesn't
// collapse cleanly to CommandModule<any, any> on its own.
const publicCommands = commands.filter((c) => c !== DevSetupCommand && c !== DevAliasCommand) as CommandModule<
  any,
  any
>[]

const table = await generateCommandTable({ commands: publicCommands })
await Bun.write(TABLE_PATH, `<!-- Auto-generated by script/generate-cli-docs.ts — do not edit manually -->\n\n${table}`)
console.log(`wrote ${TABLE_PATH}`)

const cwd = process.cwd()
const reference = (await generateHelp({ all: true, format: "md", commands: publicCommands })).replaceAll(cwd, ".")
await Bun.write(
  REFERENCE_PATH,
  `---
title: "CLI Command Reference"
description: "Complete reference for all Saeeol CLI commands and subcommands"
---

# CLI Command Reference

<!-- Auto-generated by script/generate-cli-docs.ts — do not edit manually -->

${reference}`,
)
console.log(`wrote ${REFERENCE_PATH}`)
