// ─── Crafting Preparation System ────────────────────────────────────────────
// Preparation system functions extracted from crafting-slice.ts

import type { EquipmentInstance, PreparationProgress } from './types';
import { calculatePrepTime, calculatePrepManaCost, calculateManaPerHourForPrep } from './crafting-utils';

// ─── Preparation Validation ─────────────────────────────────────────────────

// Check if an equipment instance can be prepared
export function canPrepareEquipment(
  instance: EquipmentInstance | undefined,
  currentTags: string[]
): { canPrepare: boolean; reason?: string } {
  if (!instance) {
    return { canPrepare: false, reason: 'Equipment instance not found' };
  }

  if (currentTags.includes('Ready for Enchantment')) {
    return { canPrepare: false, reason: 'Equipment is already prepared for enchanting' };
  }

  return { canPrepare: true };
}

// Calculate preparation resource costs
export interface PreparationCosts {
  time: number;
  manaTotal: number;
  manaPerHour: number;
  manaPerTick: number;
}

export function calculatePreparationCosts(totalCapacity: number): PreparationCosts {
  const time = calculatePrepTime(totalCapacity);
  const manaTotal = calculatePrepManaCost(totalCapacity);
  const manaPerHour = calculateManaPerHourForPrep(totalCapacity, time);
  const manaPerTick = manaPerHour * 0.04; // HOURS_PER_TICK

  return { time, manaTotal, manaPerHour, manaPerTick };
}

// ─── Preparation Progress ───────────────────────────────────────────────────

// Initialize preparation progress
export function initializePreparationProgress(
  equipmentInstanceId: string,
  totalCapacity: number,
  manaCostPaid: number = 0
): PreparationProgress {
  const costs = calculatePreparationCosts(totalCapacity);

  return {
    equipmentInstanceId,
    progress: 0,
    required: costs.time,
    manaCostPaid,
  };
}

// Calculate updated preparation progress after a tick
export interface PreparationTickResult {
  progress: number;
  manaCostPaid: number;
  manaConsumed: number;
  isComplete: boolean;
}

export function calculatePreparationTick(
  currentProgress: number,
  required: number,
  manaPerTick: number
): PreparationTickResult {
  const progress = currentProgress + 0.04; // HOURS_PER_TICK
  const manaConsumed = manaPerTick;
  const manaCostPaid = manaPerTick; // Accumulated

  return {
    progress,
    manaCostPaid,
    manaConsumed,
    isComplete: progress >= required,
  };
}

// ─── Preparation Completion ─────────────────────────────────────────────────

// Apply preparation completion to equipment instance
export function completePreparation(
  instance: EquipmentInstance,
  manaSpent: number
): {
  updatedInstance: EquipmentInstance;
  manaRecovered: number;
  logMessage: string;
} {
  // Calculate mana recovery from disenchanting (disenchanting skill removed - Bug 13)
  const disenchantLevel = 0;
  const recoveryRate = 0.1 + disenchantLevel * 0.2; // 10% base + 20% per level

  let totalRecovered = 0;
  for (const ench of instance.enchantments) {
    totalRecovered += Math.floor(ench.actualCost * recoveryRate);
  }

  const updatedInstance: EquipmentInstance = {
    ...instance,
    enchantments: [],
    usedCapacity: 0,
    rarity: 'common',
    tags: [...(instance.tags || []), 'Ready for Enchantment'],
  };

  return {
    updatedInstance,
    manaRecovered: totalRecovered,
    logMessage: `✅ Equipment prepared for enchanting! Recovered ${totalRecovered} mana.`,
  };
}

// Cancel preparation (no resource recovery for preparation itself)
export function cancelPreparation() {
  return {
    logMessage: 'Preparation cancelled.',
  };
}

// ─── Preparation State Calculations ─────────────────────────────────────────

export function getPreparationManaCostForTick(instance: EquipmentInstance): number {
  const costs = calculatePreparationCosts(instance.totalCapacity);
  return costs.manaPerTick;
}

export function getPreparationRemainingTime(currentProgress: number, required: number): number {
  return Math.max(0, required - currentProgress);
}

export function getPreparationCompletionPercent(currentProgress: number, required: number): number {
  return Math.min(100, Math.floor((currentProgress / required) * 100));
}
