/**
 * Shared utilities for resolving page file paths used in agent prompt generation.
 */

/** camelCase → PascalCase (first char uppercased) */
function toPascalCase(str: string): string {
  return str.charAt(0).toUpperCase() + str.slice(1);
}

/**
 * Resolve the actual routes/ directory name.
 *
 * sourceFilePath (e.g. "src/routes/iTActivityDay/list.tsx") is the ground truth
 * because the generator writes the real directory name there.
 * Falls back to resourceName (kebab-case from URL) only when unavailable.
 *
 * Example: "src/routes/iTActivityDay/list.tsx" → "iTActivityDay"
 */
export function resolveSourceDir(
  sourceFilePath: string | null | undefined,
  resourceName: string,
): string {
  if (sourceFilePath) {
    return sourceFilePath.replace(/^src\/routes\//, '').split('/')[0];
  }
  return resourceName;
}

export interface PagePaths {
  /** e.g. "iTActivityDay" */
  sourceDir: string;
  /** e.g. "ITActivityDay" */
  modelName: string;
  /** e.g. "web/src/routes/iTActivityDay/list.tsx" */
  pageFilePath: string;
  /** e.g. "config/ui/ITActivityDay.ts" */
  uiConfigPath: string;
  /** e.g. "server/src/modules/iTActivityDay/iTActivityDay.controller.ts" */
  backendApiPath: string;
  /** "config/prisma/" */
  prismaDir: string;
}

/**
 * Compute all standard page-related file paths from page context.
 */
export function resolvePagePaths(
  sourceFilePath: string | null | undefined,
  resourceName: string,
  pageFileName: string,
): PagePaths {
  const sourceDir = resolveSourceDir(sourceFilePath, resourceName);
  const modelName = toPascalCase(sourceDir);
  const pageFilePath = sourceFilePath
    ? `web/${sourceFilePath}`
    : `web/src/routes/${sourceDir}/${pageFileName}`;

  return {
    sourceDir,
    modelName,
    pageFilePath,
    uiConfigPath: `config/ui/${modelName}.ts`,
    backendApiPath: `server/src/modules/${sourceDir}/${sourceDir}.controller.ts`,
    prismaDir: 'config/prisma/',
  };
}
