/**
 * scripts/generate-docs/lib/context-builder.ts
 *
 * For every parsed page, compose the full Handlebars render context. This is
 * the only place that knows what each page needs (e.g. `ba-develop` page gets
 * only the BA + dev skills, not the whole 84-skill catalogue).
 */
import { VERSION } from './version';
import { collectStats, type Stats } from './stats';
import type { Skill } from './skill-parser';
import type { PageMeta } from './markdown-parser';
import type { Sidebar } from './sidebar-builder';

export interface RenderContext {
  version: string;
  page: PageMeta;
  sidebar: Sidebar;
  stats: Stats;
  /** All 84 skills, sorted by slug — available to every page */
  skills: Skill[];
  /** The subset of skills relevant to the current page (filtered by phase) */
  skillsForPage: Skill[];
  /** The body markdown rendered to HTML (passed through {{{bodyHtml}}}) */
  bodyHtml: string;
}

/**
 * Returns the subset of skills a given page is interested in showing as cards.
 * Pages not in this map get an empty array (the page template can still loop
 * over `skills` directly if it wants the full catalogue).
 */
function filterSkillsForPage(slug: string, all: Skill[]): Skill[] {
  switch (slug) {
    case 'commands':
      return all;
    case 'business-analyse':
      return [];
    case 'ba-skills':
      return all.filter((s) => s.phase === 'business-analyse');
    case 'ba-develop':
      return all.filter(
        (s) =>
          s.slug === 'ba-develop' ||
          s.slug === 'ba-develop-plan' ||
          s.slug === 'ba-create-plan-development' ||
          s.phase.startsWith('development/') ||
          s.phase === 'devCore' ||
          s.phase === 'devDomain' ||
          s.phase === 'devData' ||
          s.phase === 'devApi' ||
          s.phase === 'devFrontend'
      );
    case 'gitflow':
      return all.filter((s) => s.slug === 'gitflow');
    case 'efcore':
      return all.filter((s) => s.slug === 'efcore');
    case 'ralph-loop':
      return [];
    default:
      return [];
  }
}

export function buildContext(
  page: PageMeta,
  sidebar: Sidebar,
  allSkills: Skill[],
  stats: Stats
): RenderContext {
  return {
    version: VERSION,
    page,
    sidebar,
    stats,
    skills: allSkills,
    skillsForPage: filterSkillsForPage(page.slug, allSkills),
    bodyHtml: page.bodyHtml,
  };
}

export { collectStats };
