import type {
  CoreDefinition,
  FrameDefinition,
  MindCircuitDefinition,
  GolemEnchantmentDefinition,
  GolemDesign,
} from '@/lib/game/data/golems/types';
import type { GolemManaCost } from './types';
import { ELEMENTS } from '@/lib/game/constants/elements';

export function formatManaCost(cost: GolemManaCost): string {
  if (cost.type === 'raw') return `${cost.amount} raw`;
  const elem = cost.element ? ELEMENTS[cost.element] : null;
  return `${cost.amount} ${elem?.sym ?? ''} ${cost.element ?? ''}`.trim();
}

export function formatRequirement(req: CoreDefinition['unlockRequirement']): string {
  switch (req.type) {
    case 'attunement_level':
      return `${req.attunement} level ${req.level}`;
    case 'mana_unlocked': {
      const elem = req.manaType ? ELEMENTS[req.manaType] : null;
      return `Unlock ${elem?.sym ?? ''} ${req.manaType ?? ''}`.trim();
    }
    case 'dual_attunement':
      return `${req.attunements?.join(' + ')} level ${req.levels?.join('/')}`;
    case 'guardian_pact':
      return `${req.attunements?.join(' + ')} level ${req.levels?.join('/')} + Guardian Pact`;
    default:
      return 'Unknown';
  }
}

export function serializeDesign(
  name: string,
  core: CoreDefinition,
  frame: FrameDefinition,
  circuit: MindCircuitDefinition,
  enchantments: GolemEnchantmentDefinition[],
  selectedManaTypes: string[],
  selectedSpells: string[],
) {
  return {
    id: `design_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
    name,
    coreId: core.id,
    frameId: frame.id,
    mindCircuitId: circuit.id,
    enchantmentIds: enchantments.map(e => e.id),
    selectedManaTypes,
    selectedSpells,
  };
}

export function buildGolemDesign(
  core: CoreDefinition,
  frame: FrameDefinition,
  circuit: MindCircuitDefinition,
  enchantments: GolemEnchantmentDefinition[],
  selectedManaTypes: string[],
  selectedSpells: string[],
): GolemDesign {
  return {
    id: `design_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
    name: `${core.name.split(' ')[0]} ${frame.name.split(' ')[0]}`,
    core,
    frame,
    mindCircuit: circuit,
    enchantments,
    selectedManaTypes,
    selectedSpells,
  };
}
