import type { Character } from "../types";
import { getModifier } from "./modifiers";
import { getEffectiveStat, getTalentAcBonus } from "./talent-effects";

export interface AcBreakdown {
  calculated: number;
  override: number | null;
  effective: number;
  source: string;
}

export function calculateAC(character: Character): AcBreakdown {
  const dexMod = getModifier(getEffectiveStat(character, "DEX"));

  let base = 10 + dexMod;
  let source = "Unarmored";

  // Find equipped armor (not shields)
  const armor = character.gear.find(
    (g) => g.type === "armor" && g.effects.ac_base !== undefined,
  );
  if (armor) {
    const acBase = armor.effects.ac_base as number;
    const acDex = armor.effects.ac_dex as boolean;
    base = acDex ? acBase + dexMod : acBase;
    source = armor.name;
  }

  // Find shield
  const shield = character.gear.find(
    (g) => g.type === "armor" && g.effects.ac_bonus !== undefined,
  );
  if (shield) {
    base += shield.effects.ac_bonus as number;
    source += " + " + shield.name;
  }

  // Talent AC bonuses (e.g. Shield of Faith)
  const talentAcBonus = getTalentAcBonus(character);
  if (talentAcBonus > 0) {
    base += talentAcBonus;
    source += " + talents";
  }

  const override = (character.overrides?.ac as number | undefined) ?? null;

  return {
    calculated: base,
    override: override,
    effective: override ?? base,
    source,
  };
}
