import { bossMechanicName } from "./bosses/mechanicPool";
import type { BossId, BossMechanicId } from "./types";

export type BossArchetype =
  | "bull"
  | "web-caster"
  | "sky-sweeper"
  | "duelist"
  | "ram"
  | "ricochet"
  | "burrower"
  | "crab"
  | "ghost"
  | "golem";

export type BossGroupId =
  | "charge"
  | "bind-venom"
  | "breath-skyfall"
  | "slash-cross"
  | "ricochet"
  | "burrow-eruption"
  | "scuttle-burst"
  | "rift-lanes"
  | "shockwave-fall";

export type BossGroupLetter = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I";

export interface BossGroupDefinition {
  id: BossGroupId;
  letter: BossGroupLetter;
  name: string;
  coreMechanic: string;
  bossIds: readonly BossId[];
  archetypes: readonly BossArchetype[];
}

export interface BossDefinition {
  id: BossId;
  name: string;
  title: string;
  trial: string;
  icon: string;
  accent: string;
  summary: string;
  briefing: string;
  failure: string;
  mapTitle: string;
  mapCopy: string;
  mechanicIds: readonly [BossMechanicId, BossMechanicId, ...BossMechanicId[]];
  maxHp: number;
  archetype: BossArchetype;
  groupId: BossGroupId;
}

interface BossSeed {
  name: string;
  title: string;
  icon: string;
  accent: string;
  summary: string;
  mechanicIds: readonly [BossMechanicId, BossMechanicId, ...BossMechanicId[]];
  maxHp: number;
  archetype: BossArchetype;
}

function boss(id: BossId, index: number, seed: BossSeed): BossDefinition {
  const [firstId, secondId] = seed.mechanicIds;
  const first = bossMechanicName(firstId);
  const second = bossMechanicName(secondId);
  const mechanicIds = [...seed.mechanicIds, "basic-melee"] as BossDefinition["mechanicIds"];
  return {
    id,
    ...seed,
    mechanicIds,
    groupId: BOSS_GROUP_BY_BOSS_ID[id],
    trial: `Trial ${String(index + 1).padStart(2, "0")} · ${seed.title}`,
    briefing: `Read ${first}, then preserve open ground for ${second}.`,
    failure: `Do not overlap ${first}. Re-form only after ${second} resolves.`,
    mapTitle: seed.title,
    mapCopy: `${seed.summary} Keep escape lanes open and move before each warning completes.`,
  };
}

const BOSS_SEEDS: Record<BossId, BossSeed> = {
  bulldrome: {
    name: "Bulldrome", title: "Hall of the Cinder Bull", icon: "♜", accent: "#e2744e",
    summary: "Charges marked lanes and crushes grouped targets.", mechanicIds: ["bull-charge", "crushing-pounce", "cinder-nova", "ember-brand"], maxHp: 500, archetype: "bull",
  },
  "sandglass-scorpion": {
    name: "Sandglass Scorpion", title: "The Sunken Hour", icon: "⌛", accent: "#e9b94f",
    summary: "Burrows beneath marked paths and erupts through timed hourglass zones.", mechanicIds: ["burrow-rush", "hourglass-eruption", "memory-sequence"], maxHp: 515, archetype: "burrower",
  },
  "cragclaw-crab": {
    name: "Cragclaw", title: "The Drowned Breakwater", icon: "♋", accent: "#49c7d4",
    summary: "Scuttles through marked lanes and crushes the arena beneath tidal bursts.", mechanicIds: ["sidewinder-rush", "crushing-tide", "aetheric-soak"], maxHp: 505, archetype: "crab",
  },
  "mournveil-ghost": {
    name: "Mournveil", title: "The Silent Reliquary", icon: "◉", accent: "#9d72ff",
    summary: "Cuts the arena twice with spectral lanes and leaves hungry rifts beneath allies.", mechanicIds: ["vine-scissors", "haunting-rifts", "soul-siphon"], maxHp: 505, archetype: "ghost",
  },
  "crownshard-golem": {
    name: "Crownshard Golem", title: "The Broken Coronation", icon: "♛", accent: "#e0bd45",
    summary: "Sends royal shockwaves across the floor and calls crushing crown shards from above.", mechanicIds: ["tri-burst", "ultimate-skyfall", "aetheric-soak"], maxHp: 500, archetype: "golem",
  },
  "crystal-bat-matriarch": {
    name: "Crystal Bat Matriarch", title: "The Prism Echo", icon: "◈", accent: "#8eeaff",
    summary: "Sonic rings force precise spacing while orbiting mirror shards fracture safe ground.", mechanicIds: ["tri-burst", "prism-beam", "memory-sequence"], maxHp: 480, archetype: "golem",
  },
  "stormwool-alpaca": {
    name: "Stormwool", title: "The Thunder Fleece", icon: "ϟ", accent: "#8fc7ff",
    summary: "Gallops through charged lanes before crashing onto the marked healer.", mechanicIds: ["bull-charge", "crushing-pounce", "stormfall"], maxHp: 480, archetype: "bull",
  },
  "cluckhorn-colossus": {
    name: "Brassbeak Basilisk", title: "The Furnace Nest", icon: "✹", accent: "#dba33e",
    summary: "Scuttles through lateral lanes and vents furnace bursts on spread targets.", mechanicIds: ["sidewinder-rush", "crushing-tide", "meteor-spread"], maxHp: 475, archetype: "crab",
  },
  "ashwing-demon": {
    name: "Ashwing", title: "The Cinder Choir", icon: "♠", accent: "#df665d",
    summary: "Carves crossing fire lanes and opens persistent ember rifts.", mechanicIds: ["vine-scissors", "haunting-rifts", "cinder-nova"], maxHp: 515, archetype: "ghost",
  },
  "riftclaw-demon": {
    name: "Riftclaw", title: "The Broken Duel", icon: "⚔", accent: "#d45cff",
    summary: "Sidesteps around the tank before cutting single and crossed void lanes.", mechanicIds: ["elemental-beam", "guardian-cross", "soul-siphon"], maxHp: 495, archetype: "duelist",
  },
  "tempestscale-dragon": {
    name: "Tempestscale", title: "The Living Storm", icon: "☈", accent: "#5fc8e8",
    summary: "Sweeps the arena with storm breath before marking allies for sky strikes.", mechanicIds: ["storm-breath", "stormfall", "prism-beam"], maxHp: 500, archetype: "sky-sweeper",
  },
  emberfox: {
    name: "Emberfox", title: "The Burning Trail", icon: "✦", accent: "#ff7b45",
    summary: "Ricochets across the arena and leaves fire at every landing.", mechanicIds: ["ricochet-rush", "meteor-slam", "ember-brand"], maxHp: 465, archetype: "ricochet",
  },
  "mirelord-frog": {
    name: "Bogbell Myconid", title: "The Drowned Bell", icon: "●", accent: "#8fdc69",
    summary: "Roots below the mire before erupting through timed spore blooms.", mechanicIds: ["burrow-rush", "hourglass-eruption", "hollow-collapse"], maxHp: 490, archetype: "burrower",
  },
  "stonebreaker-giant": {
    name: "Stonebreaker", title: "The Walking Crag", icon: "▰", accent: "#c89563",
    summary: "Sends quake bands across the floor and rains boulders on spread allies.", mechanicIds: ["tri-burst", "ruin-quake", "meteor-spread"], maxHp: 500, archetype: "golem",
  },
  "glub-sovereign": {
    name: "Glub Sovereign", title: "The Binding Ooze", icon: "◌", accent: "#6ce0b8",
    summary: "Links two allies with living slime before seeding toxic pools.", mechanicIds: ["binding-web", "venom-purge", "hollow-collapse"], maxHp: 495, archetype: "web-caster",
  },
  "scrapking-goblin": {
    name: "Scrapking", title: "The Jagged Throne", icon: "⚒", accent: "#d7a34b",
    summary: "Repositions between attacks and fires improvised blade lanes.", mechanicIds: ["elemental-beam", "guardian-cross", "meteor-spread"], maxHp: 485, archetype: "duelist",
  },
  "warcaller-orc": {
    name: "Warcaller", title: "The Red Standard", icon: "⚑", accent: "#e4533f",
    summary: "Tracks the party flank before cleaving single and crossed war lanes.", mechanicIds: ["elemental-beam", "guardian-cross", "aetheric-soak"], maxHp: 500, archetype: "duelist",
  },
  "tuskmaw-orc": {
    name: "Tuskmaw", title: "The Breaker Below", icon: "◈", accent: "#9eb25d",
    summary: "Rushes laterally and crushes three marked allies beneath tusk bursts.", mechanicIds: ["sidewinder-rush", "crushing-tide", "destruction-pulse"], maxHp: 525, archetype: "crab",
  },
  "broodfang-spider": {
    name: "Broodfang", title: "The Silk Tyrant", icon: "✣", accent: "#b56cff",
    summary: "Binds paired prey with silk before flooding safe ground with venom.", mechanicIds: ["binding-web", "venom-purge", "meteor-spread"], maxHp: 535, archetype: "web-caster",
  },
  "silkfang-spider": {
    name: "Silkfang", title: "The Gloom Weaver", icon: "✤", accent: "#9d68d8",
    summary: "Snares paired allies before seeding the arena with toxic nests.", mechanicIds: ["binding-web", "venom-purge", "soul-siphon"], maxHp: 505, archetype: "web-caster",
  },
  "thorncrown-stag": {
    name: "Thorncrown", title: "The Briar Hart", icon: "♧", accent: "#7fc46b",
    summary: "Charges through thorn lanes and leaps onto grouped prey.", mechanicIds: ["bull-charge", "crushing-pounce", "hollow-collapse"], maxHp: 510, archetype: "bull",
  },
  "sky-totem": {
    name: "Sky Totem", title: "The Hollow Idol", icon: "☼", accent: "#69d4d1",
    summary: "Cuts the floor with spirit lanes and anchors hungry wind rifts.", mechanicIds: ["vine-scissors", "haunting-rifts", "prism-beam"], maxHp: 505, archetype: "ghost",
  },
  "razorcrest-raptor": {
    name: "Razorcrest", title: "The Hunting Circuit", icon: "➳", accent: "#d9c45a",
    summary: "Rebounds through hunting lanes and tears open impact pools.", mechanicIds: ["ricochet-rush", "meteor-slam", "prism-beam"], maxHp: 500, archetype: "ricochet",
  },
  "bristlequake-boar": {
    name: "Bristlequake", title: "The Iron Tusk", icon: "♞", accent: "#d47b45",
    summary: "Breaks formation with armored rushes, quakes, and radial fault lines.", mechanicIds: ["destruction-rush", "ruin-quake", "destruction-pulse"], maxHp: 545, archetype: "ram",
  },
  "moonfang-wolf": {
    name: "Moonfang", title: "The Silver Pursuit", icon: "☾", accent: "#9db9e5",
    summary: "Ricochets between marked lanes and leaves moonfire at each strike.", mechanicIds: ["ricochet-rush", "meteor-slam", "soul-siphon"], maxHp: 495, archetype: "ricochet",
  },
  "frostmaw-yeti": {
    name: "Frostmaw", title: "The White Avalanche", icon: "❄", accent: "#8ed8ef",
    summary: "Scuttles through ice lanes and buries spread allies beneath frost bursts.", mechanicIds: ["sidewinder-rush", "crushing-tide", "hollow-collapse"], maxHp: 550, archetype: "crab",
  },
  "rimeclaw-yeti": {
    name: "Rimeclaw", title: "The Frozen Duel", icon: "✥", accent: "#75bfe8",
    summary: "Sidesteps between frost strikes before forming a lethal ice cross.", mechanicIds: ["elemental-beam", "guardian-cross", "memory-sequence"], maxHp: 500, archetype: "duelist",
  },
  "gravehorn-triceratops": {
    name: "Gravehorn", title: "The Fossil Wake", icon: "☠", accent: "#d8c79b",
    summary: "Burrows through fossil trails, erupts beneath the party, and releases a radial grave pulse.", mechanicIds: ["burrow-rush", "hourglass-eruption", "destruction-pulse"], maxHp: 540, archetype: "burrower",
  },
};

/**
 * Loot and encounter organization. Archetypes still select existing combat
 * scripts; groups describe the shared core mechanic and reward material.
 */
export const BOSS_GROUPS: readonly BossGroupDefinition[] = [
  {
    id: "charge", letter: "A", name: "Charge", coreMechanic: "Charge",
    bossIds: ["bulldrome", "stormwool-alpaca", "thorncrown-stag", "bristlequake-boar"], archetypes: ["bull", "ram"],
  },
  {
    id: "bind-venom", letter: "B", name: "Bind / Venom", coreMechanic: "Bind and Venom",
    bossIds: ["glub-sovereign", "broodfang-spider", "silkfang-spider"], archetypes: ["web-caster"],
  },
  {
    id: "breath-skyfall", letter: "C", name: "Breath / Skyfall", coreMechanic: "Breath and Skyfall",
    bossIds: ["tempestscale-dragon"], archetypes: ["sky-sweeper"],
  },
  {
    id: "slash-cross", letter: "D", name: "Slash / Cross", coreMechanic: "Slash and Cross",
    bossIds: ["riftclaw-demon", "scrapking-goblin", "warcaller-orc", "rimeclaw-yeti"], archetypes: ["duelist"],
  },
  {
    id: "ricochet", letter: "E", name: "Ricochet", coreMechanic: "Ricochet",
    bossIds: ["emberfox", "razorcrest-raptor", "moonfang-wolf"], archetypes: ["ricochet"],
  },
  {
    id: "burrow-eruption", letter: "F", name: "Burrow / Eruption", coreMechanic: "Burrow and Eruption",
    bossIds: ["sandglass-scorpion", "mirelord-frog", "gravehorn-triceratops"], archetypes: ["burrower"],
  },
  {
    id: "scuttle-burst", letter: "G", name: "Scuttle / Burst", coreMechanic: "Scuttle and Burst",
    bossIds: ["cragclaw-crab", "cluckhorn-colossus", "tuskmaw-orc", "frostmaw-yeti"], archetypes: ["crab"],
  },
  {
    id: "rift-lanes", letter: "H", name: "Rift / Lanes", coreMechanic: "Rifts and Lanes",
    bossIds: ["mournveil-ghost", "ashwing-demon", "sky-totem"], archetypes: ["ghost"],
  },
  {
    id: "shockwave-fall", letter: "I", name: "Shockwave / Fall", coreMechanic: "Shockwave and Fall",
    bossIds: ["crownshard-golem", "crystal-bat-matriarch", "stonebreaker-giant"], archetypes: ["golem"],
  },
] as const;

export const BOSS_GROUP_BY_ID = Object.fromEntries(
  BOSS_GROUPS.map((group) => [group.id, group]),
) as Record<BossGroupId, BossGroupDefinition>;

export const BOSS_GROUP_BY_BOSS_ID = Object.fromEntries(
  BOSS_GROUPS.flatMap((group) => group.bossIds.map((bossId) => [bossId, group.id])),
) as Record<BossId, BossGroupId>;

export function bossGroupFor(bossId: BossId): BossGroupDefinition {
  return BOSS_GROUP_BY_ID[BOSS_GROUP_BY_BOSS_ID[bossId]];
}

/**
 * Canonical roster. Adding a boss definition makes it eligible for every
 * encounter surface, including the dungeon selector and roguelike pool.
 */
export const AVAILABLE_BOSS_IDS = Object.freeze(Object.keys(BOSS_SEEDS) as BossId[]);

export const BOSS_DEFINITIONS = Object.fromEntries(
  AVAILABLE_BOSS_IDS.map((id, index) => [id, boss(id, index, BOSS_SEEDS[id])]),
) as Record<BossId, BossDefinition>;

export const BOSS_ARCHETYPE_BY_ID = Object.fromEntries(
  AVAILABLE_BOSS_IDS.map((id) => [id, BOSS_DEFINITIONS[id].archetype]),
) as Record<BossId, BossArchetype>;
