// ─── Golem Helper Functions ─────────────────────────

import type { GolemDef, GolemManaCost } from './types';
import { GOLEMS_DEF } from './golems-data';

// Get golem slots based on Fabricator attunement level
// Level 2 = 1, Level 4 = 2, Level 6 = 3, Level 8 = 4, Level 10 = 5
export function getGolemSlots(fabricatorLevel: number): number {
  if (fabricatorLevel < 2) return 0;
  return Math.floor(fabricatorLevel / 2);
}

// Check if a golem is unlocked based on player state
export function isGolemUnlocked(
  golemId: string,
  attunements: Record<string, { active: boolean; level: number }>,
  unlockedElements: string[]
): boolean {
  const golem = GOLEMS_DEF[golemId];
  if (!golem) return false;
  
  const condition = golem.unlockCondition;
  
  switch (condition.type) {
    case 'attunement_level':
      const attState = attunements[condition.attunement || ''];
      return attState?.active && (attState.level || 1) >= (condition.level || 1);
    
    case 'mana_unlocked':
      return unlockedElements.includes(condition.manaType || '');
    
    case 'dual_attunement':
      if (!condition.attunements || !condition.levels) return false;
      return condition.attunements.every((attId, idx) => {
        const att = attunements[attId];
        return att?.active && (att.level || 1) >= condition.levels![idx];
      });
    
    default:
      return false;
  }
}

// Get all unlocked golems for a player
export function getUnlockedGolems(
  attunements: Record<string, { active: boolean; level: number }>,
  unlockedElements: string[]
): GolemDef[] {
  return Object.values(GOLEMS_DEF).filter(golem => 
    isGolemUnlocked(golem.id, attunements, unlockedElements)
  ) as GolemDef[];
}

// Calculate golem damage with skill bonuses
export function getGolemDamage(
  golemId: string,
  skills: Record<string, number>
): number {
  const golem = GOLEMS_DEF[golemId];
  if (!golem) return 0;
  
  let damage = golem.damage;
  
  // Golem Mastery skill bonus
  const masteryBonus = 1 + (skills.golemMastery || 0) * 0.1;
  damage *= masteryBonus;
  
  return damage;
}

// Calculate golem attack speed with skill bonuses
export function getGolemAttackSpeed(
  golemId: string,
  skills: Record<string, number>
): number {
  const golem = GOLEMS_DEF[golemId];
  if (!golem) return 0;
  
  let speed = golem.attackSpeed;
  
  // Golem Efficiency skill bonus
  const efficiencyBonus = 1 + (skills.golemEfficiency || 0) * 0.05;
  speed *= efficiencyBonus;
  
  return speed;
}

// Get floors golems can last (base 1, +1 per Golem Longevity skill level)
export function getGolemFloorDuration(skills: Record<string, number>): number {
  return 1 + (skills.golemLongevity || 0);
}

// Get maintenance cost multiplier (Golem Siphon reduces by 10% per level)
export function getGolemMaintenanceMultiplier(skills: Record<string, number>): number {
  return 1 - (skills.golemSiphon || 0) * 0.1;
}

// Check if player can afford golem summon cost
export function canAffordGolemSummon(
  golemId: string,
  rawMana: number,
  elements: Record<string, { current: number; max: number; unlocked: boolean }>
): boolean {
  const golem = GOLEMS_DEF[golemId];
  if (!golem) return false;
  
  for (const cost of golem.summonCost) {
    if (cost.type === 'raw') {
      if (rawMana < cost.amount) return false;
    } else if (cost.element) {
      const elem = elements[cost.element];
      if (!elem || !elem.unlocked || elem.current < cost.amount) return false;
    }
  }
  
  return true;
}

// Deduct golem summon cost from mana pools
export function deductGolemSummonCost(
  golemId: string,
  rawMana: number,
  elements: Record<string, { current: number; max: number; unlocked: boolean }>
): { rawMana: number; elements: Record<string, { current: number; max: number; unlocked: boolean }> } {
  const golem = GOLEMS_DEF[golemId];
  if (!golem) return { rawMana, elements };
  
  let newRawMana = rawMana;
  let newElements = { ...elements };
  
  for (const cost of golem.summonCost) {
    if (cost.type === 'raw') {
      newRawMana -= cost.amount;
    } else if (cost.element && newElements[cost.element]) {
      newElements = {
        ...newElements,
        [cost.element]: {
          ...newElements[cost.element],
          current: newElements[cost.element].current - cost.amount,
        },
      };
    }
  }
  
  return { rawMana: newRawMana, elements: newElements };
}

// Check if player can afford golem maintenance for one tick
export function canAffordGolemMaintenance(
  golemId: string,
  rawMana: number,
  elements: Record<string, { current: number; max: number; unlocked: boolean }>,
  skills: Record<string, number>
): boolean {
  const golem = GOLEMS_DEF[golemId];
  if (!golem) return false;
  
  const maintenanceMult = getGolemMaintenanceMultiplier(skills);
  
  for (const cost of golem.maintenanceCost) {
    const adjustedAmount = cost.amount * maintenanceMult;
    if (cost.type === 'raw') {
      if (rawMana < adjustedAmount) return false;
    } else if (cost.element) {
      const elem = elements[cost.element];
      if (!elem || !elem.unlocked || elem.current < adjustedAmount) return false;
    }
  }
  
  return true;
}

// Deduct golem maintenance cost for one tick
export function deductGolemMaintenance(
  golemId: string,
  rawMana: number,
  elements: Record<string, { current: number; max: number; unlocked: boolean }>,
  skills: Record<string, number>
): { rawMana: number; elements: Record<string, { current: number; max: number; unlocked: boolean }> } {
  const golem = GOLEMS_DEF[golemId];
  if (!golem) return { rawMana, elements };
  
  const maintenanceMult = getGolemMaintenanceMultiplier(skills);
  
  let newRawMana = rawMana;
  let newElements = { ...elements };
  
  for (const cost of golem.maintenanceCost) {
    const adjustedAmount = cost.amount * maintenanceMult;
    if (cost.type === 'raw') {
      newRawMana -= adjustedAmount;
    } else if (cost.element && newElements[cost.element]) {
      newElements = {
        ...newElements,
        [cost.element]: {
          ...newElements[cost.element],
          current: newElements[cost.element].current - adjustedAmount,
        },
      };
    }
  }
  
  return { rawMana: newRawMana, elements: newElements };
}
