import path from "node:path";
import type { CommandResult } from "../../../lib/command-result";
import { runGenerateDoc } from "../../../lib/generate-doc";
import { APP_PATHS } from "../../../lib/paths";
import { APP_COMPOSE_SCHEMAS } from "../../schemas";

export const APP_DOC_TYPES = ["actor", "business-flow", "story", "screen", "resolver"] as const;

export type AppDocType = (typeof APP_DOC_TYPES)[number];

// business-flow and story have special path shapes and are handled separately
const DIR_MAP = {
  actor: APP_PATHS.docs.actor,
  screen: APP_PATHS.docs.screen,
  resolver: APP_PATHS.docs.resolver,
} as const;

export function resolveAppDocPath(
  type: AppDocType,
  name: string | undefined,
  appPath: string,
): string {
  if (!name) {
    throw new Error(`Name is required for doc type "${type}"`);
  }

  if (type === "business-flow") {
    return path.join(appPath, APP_PATHS.docs.businessFlow, name, "README.md");
  }

  if (type === "story") {
    const parts = name.split("/");
    if (parts.length !== 2) {
      throw new Error(
        `Story name must be "<flow>/<story>" (e.g., "onboarding/admin--create-user")`,
      );
    }
    return path.join(
      appPath,
      APP_PATHS.docs.businessFlow,
      parts[0],
      APP_PATHS.docs.story,
      `${parts[1]}.md`,
    );
  }

  return path.join(appPath, DIR_MAP[type], `${name}.md`);
}

export function runAppGenerateDoc(
  type: AppDocType,
  name: string | undefined,
  appPath: string,
  cwd: string,
): Promise<CommandResult> {
  return runGenerateDoc(resolveAppDocPath(type, name, appPath), APP_COMPOSE_SCHEMAS[type], cwd);
}
