import {
  readEvidenceSummaryForMenu,
  type FrameworkMenuEvidenceSummary,
} from './framework-menu-evidence-summary-lib';
import {
  renderLegacyPanel,
  resolveLegacyPanelOuterWidth,
} from './framework-menu-legacy-audit-lib';
import { resolveConsumerMenuLayout } from './framework-menu-layout-lib';
import {
  buildCliDesignTokens,
  renderActionRow,
  renderBadge,
} from './framework-menu-ui-components-lib';
import { isMenuUiV2Enabled } from './framework-menu-ui-version-lib';
import type {
  ConsumerAction,
  ConsumerRuntimeWrite,
} from './framework-menu-consumer-runtime-types';

const PUMUKI_LEGACY_BANNER = [
  '██████╗ ██╗   ██╗███╗   ███╗██╗   ██╗██╗  ██╗██╗',
  '██╔══██╗██║   ██║████╗ ████║██║   ██║██║ ██╔╝██║',
  '██████╔╝██║   ██║██╔████╔██║██║   ██║█████╔╝ ██║',
  '██╔═══╝ ██║   ██║██║╚██╔╝██║██║   ██║██╔═██╗ ██║',
  '██║     ╚██████╔╝██║ ╚═╝ ██║╚██████╔╝██║  ██╗██║',
  '╚═╝      ╚═════╝ ╚═╝     ╚═╝ ╚═════╝ ╚═╝  ╚═╝╚═╝',
  '                      🐈 En memoria de Pumuki 💚',
];

const buildConsumerRuntimeMenuStatus = (
  menuSummary: FrameworkMenuEvidenceSummary
): { level: 'info' | 'block' | 'warn' | 'ok'; label: string } =>
  menuSummary.status !== 'ok'
    ? { level: 'info', label: 'NO_EVIDENCE' }
    : (menuSummary.outcome ?? 'UNKNOWN').trim().toUpperCase() === 'BLOCK'
      ? { level: 'block', label: 'BLOCK' }
      : (menuSummary.outcome ?? 'UNKNOWN').trim().toUpperCase() === 'WARN'
        ? { level: 'warn', label: 'WARN' }
        : (menuSummary.outcome ?? 'UNKNOWN').trim().toUpperCase() === 'PASS'
          ? { level: 'ok', label: 'PASS' }
          : { level: 'info', label: (menuSummary.outcome ?? 'UNKNOWN').trim().toUpperCase() };

export const renderConsumerRuntimeClassicMenu = (
  actions: ReadonlyArray<ConsumerAction>,
  useColor: () => boolean
): string => {
  const actionById = new Map(actions.map((action) => [action.id, action]));
  const label = (id: string): string => actionById.get(id)?.label ?? 'Unavailable';
  const lines = [
    ...PUMUKI_LEGACY_BANNER,
    '',
    'Advanced Project Audit — AST Intelligence & Quality Gate',
    '',
    `1) ${label('1')}   6) ${label('6')}`,
    `2) ${label('2')}  7) ${label('7')}`,
    `3) ${label('3')}    8) ${label('8')}`,
    `4) ${label('4')}       9) ${label('9')}`,
    `5) ${label('5')}                 10) ${label('10')}`,
    '',
    'Additional engine flows',
    `11) ${label('11')}`,
    `12) ${label('12')}`,
    `13) ${label('13')}`,
    `14) ${label('14')}`,
    '',
    'A) Switch to advanced menu',
  ];
  return renderLegacyPanel(lines, {
    width: resolveLegacyPanelOuterWidth(),
    color: useColor(),
  });
};

export const renderConsumerRuntimeModernMenu = (
  params: {
    actions: ReadonlyArray<ConsumerAction>;
    repoRoot: string;
    useColor: () => boolean;
  }
): string => {
  const menuSummary = readEvidenceSummaryForMenu(params.repoRoot);
  const menuStatus = buildConsumerRuntimeMenuStatus(menuSummary);
  const tokens = buildCliDesignTokens({
    width: resolveLegacyPanelOuterWidth(),
    color: params.useColor(),
  });
  const groupedActions = resolveConsumerMenuLayout(params.actions);
  const lines = [
    ...PUMUKI_LEGACY_BANNER,
    '',
    'Advanced Project Audit — AST Intelligence & Quality Gate',
    `Status: ${renderBadge(menuStatus.label, menuStatus.level, tokens)}`,
    'A. Switch to advanced menu',
    '',
    ...groupedActions.flatMap((group) => [
      group.title,
      ...group.items.map((item) => renderActionRow({
        id: item.id,
        label: item.action.label,
      })),
      '',
    ]),
  ];
  return renderLegacyPanel(lines, {
    width: resolveLegacyPanelOuterWidth(),
    color: params.useColor(),
  });
};

export const printConsumerRuntimeMenu = (params: {
  actions: ReadonlyArray<ConsumerAction>;
  repoRoot: string;
  useColor: () => boolean;
  write: ConsumerRuntimeWrite;
}): void => {
  const classicMenu = renderConsumerRuntimeClassicMenu(params.actions, params.useColor);
  if (!isMenuUiV2Enabled()) {
    params.write(`\n${classicMenu}\n`);
    return;
  }

  try {
    params.write(`\n${renderConsumerRuntimeModernMenu({
      actions: params.actions,
      repoRoot: params.repoRoot,
      useColor: params.useColor,
    })}\n`);
  } catch {
    params.write('\n[pumuki][menu-ui-v2] Render failed. Falling back to classic menu.\n');
    params.write(`\n${classicMenu}\n`);
  }
};
