# Guilds, Raids, Wars, and Guild Bosses

## Overview
Guilds are persistent player groups with a shared bank, leveling, raid/war PvP, cosmetic banners, achievement tracking, and a rotating global guild boss. The live code uses one guild core system, but it exposes **three distinct gameplay loops**:

1. **Guild management** - create, invite, join, upgrade, deposit, withdraw, banner management
2. **Guild raids / guild wars** - PvP between guilds
3. **Guild boss** - a shared PvE boss attacked by guild members across the server

## Commands

### Guild core

| Command | What it does | Notes |
|---|---|---|
| `.guild create <name>` | Creates a guild | Costs 20,000 coins |
| `.guild info` | Shows guild summary | UI-rich response |
| `.guild members` | Lists members | Shows current size and cap |
| `.guild invite @user` | Invites a player | Leader only |
| `.guild accept` | Accepts latest guild invite | Target guild must still have room |
| `.guild reject` | Rejects latest guild invite | - |
| `.guild leave` | Leaves the guild | Solo leader leaving disbands the guild |
| `.guild kick @user` | Removes a member | Leader only |
| `.guild deposit <amount>` | Adds coins to guild bank | Any member |
| `.guild withdraw <amount>` | Splits a withdrawal evenly across all members | Leader only |
| `.guild upgrade` | Adds +1 guild slot | Costs 250 Cash |
| `.guild achievements` | Shows guild achievement unlocks | Reads `guild_achievements` |
| `.guild leaderboard` | Shows top guilds | Sorted by season points -> weekly points -> raid points -> level |
| `.guild perk status` | Shows currently active guild stat perk | - |
| `.guild perk buy <common|rare>` | Activates a 12h combat stat perk | Leader only, bank coins |

### Guild wars

| Command | What it does | Notes |
|---|---|---|
| `.guild war @guildname [@member1 @member2 ...]` | Sends a war challenge | Leader only |
| `.guild war accept` | Accepts the pending war challenge | Defender leader only |
| `.guild war decline` | Declines the pending war challenge | Defender leader only |

### Guild raids and banners

| Command | What it does | Notes |
|---|---|---|
| `.raid @guildname` | Starts a guild raid | Leader only |
| `.banner shop` | Shows banner shop | - |
| `.banner buy <bannerId>` | Buys a guild banner | Leader only; paid by leader's coins |
| `.banner equip <bannerId>` | Equips an owned banner | Leader only |

### Guild boss

| Command | What it does | Notes |
|---|---|---|
| `.guild boss` | Shows boss status or time until next spawn | - |
| `.guild boss attack` | Attacks the active guild boss | 10-minute cooldown per player |

## Core Mechanics

### Creation and membership
- Guild creation cost: **20,000 coins**.
- Guild names:
  - cannot contain spaces,
  - max length **24**,
  - must be unique case-insensitively.
- Default capacity: **4 members**.
- Maximum capacity: **8 members**.
- Each `.guild upgrade` costs **250 Cash** and increases cap by **1**.

### Leaving and disbanding
- A non-leader can leave freely with `.guild leave`.
- A leader **cannot** leave while other members remain.
- If the leader is the only member and uses `.guild leave`, the guild is disbanded.
- There is **no separate `.guild disband` command** in the live command handler.

### Guild bank
- Any member may deposit coins.
- Only the leader may withdraw.
- Withdrawals are split evenly among all current members:

```text
perMember = floor(requestedAmount / memberCount)
actualWithdrawn = perMember * memberCount
```

Any remainder from floor division is not distributed.

Withdrawals are blocked if the requested amount would dip below `guild_raid_locks.locked_coins` for that guild.

### Guild leveling
Guild XP thresholds are:

| Next Level | Total XP Threshold |
|---|---:|
| 2 | 500 |
| 3 | 1,500 |
| 4 | 4,000 |
| 5 | 9,000 |
| 6+ | `9,000 + (level - 5) * 5,000` |

XP gains from current live systems:
- successful guild raid reward path: **+300 guild XP**
- guild boss top-3 guild rewards: **+600 / +400 / +250 guild XP**

## Guild Raids

### Requirements
The attacking guild must have:
- at least **2 members**
- at least **60,000 bank coins** before fees
- a leader starting the raid

The defending guild must also have:
- at least **2 members**
- at least **60,000 bank coins**

### Entry fee
The attacker's bank pays a burned entry fee of:

```text
5,000 coins * attacker member count
```

The code also requires the attacker's bank to still remain at or above the raid minimum after covering that fee.

### Cooldowns and protection
- General raid cooldown for both guilds: **2 hours**
- Same attacker -> defender pair protection: **3 hours**

### Raid simulation
Guild raid combat builds a large merged team from each guild's active members.

Rules:
- up to **3 animals per member** are used
- each guild can field up to **18 animals** total
- equipped weapons and animal enchantments are carried into the merged raid team
- the real battle engine is used to simulate the result
- the UI receives **10 condensed guild-level snapshots** rather than every internal turn

### Raid rewards
If the attacker wins, the winner can steal up to:

```text
min(50,000, loser.bank_coins, winnerRemainingDailyCap)
```

Winner rewards on successful payout:
- up to **50,000 bank coins** stolen
- **+100 raid points**
- **+50 season points**
- **+50 weekly points**
- **+300 guild XP**

### Raid reward cap by winner member count
The code calculates the practical cap from guild size:

| Winner member count | Cap used by reward logic |
|---|---:|
| 1-10 | 50,000 |
| 11-25 | 120,000 |
| 26-50 | 250,000 |
| 51+ | 400,000 |

The tracking table is `guild_daily_raid_limits`, so the current implementation treats this as a daily-style cap.

### Enchant usage
After a guild raid, the server consumes enchantment usage for **all raid participants on both sides**.

## Guild Wars

### Requirements
- Only the leader can challenge or accept.
- Both guilds need at least **3 members**.
- War challenge lifetime: **2 minutes**.
- The attacker can specify participants or let the system auto-pick.

### Participant limits
- Minimum attacker picks: **3**
- Maximum picks: **8**
- If no picks are supplied, the code uses the first available guild members up to 8.

### War flow
Guild Wars use `simulateGuildWar()` and run as a queued elimination sequence:
1. attacker roster is chosen,
2. defender accepts,
3. members duel in order,
4. surviving power carries forward through the war,
5. war ends when one guild runs out of participants.

### War rewards
On war end:
- winner guild: **+150 season points**, **+150 weekly points**, `war_wins + 1`
- loser guild: `war_losses + 1`

## Guild Boss

### Boss rotation
The boss scheduler rotates through this fixed list:

| Order | Boss | Base HP | Icon |
|---|---|---:|---|
| 1 | Stone Colossus | 750,000 | `boss1.svg` |
| 2 | Infernal Warlord | 1,350,000 | `boss2.svg` |
| 3 | Void Serpent | 2,250,000 | `boss3.svg` |
| 4 | Shadow Titan | 3,300,000 | `boss4.svg` |
| 5 | World Eater | 4,500,000 | `boss5.svg` |

### Spawn timing
- Boss respawn interval after a kill or despawn: **10 hours**
- Boss despawn timer: **4 hours** after spawn (if not killed within 4 hours, boss flees)
- Scheduler check frequency: **every 10 minutes**
- If no boss row exists, the first boss is created immediately.
- Boss spawn announcements appear in chat channels with a visual card.

### HP scaling
Boss HP is scaled from total guild participation on the server:

```text
scaledHp = baseHp + (count(distinct guild_members.user_id) * 50,000)
```

### Attack flow
`.guild boss attack`:
- requires the attacker to be in a guild,
- requires an active boss with `current_hp > 0`,
- uses the shared cooldown key `guild_boss_attack`, currently **10 minutes** per player.

The attack simulation:
- builds a combatant from the player's active team,
- includes equipped weapon stats and reroll bonuses,
- runs a short skirmish against the boss,
- applies the resulting damage to the singleton boss row,
- updates both per-player and per-guild damage leaderboards.
- Boss cards display top 5 guilds by total damage in real-time.

### Guild boss rewards on death
#### Guild rewards
Top 3 guilds by total damage receive:

| Rank | Bank Coins | Raid Points | Guild XP |
|---|---:|---:|---:|
| 1 | 350,000 | 200 | 600 |
| 2 | 200,000 | 120 | 400 |
| 3 | 100,000 | 80 | 250 |

Every contributing guild also gets:
- **+100 season points**
- **+100 weekly points**

### Enchant usage
After each boss attack, the attacker's enchantment usage is consumed once.

## Guild Perks

Guild leaders can spend coins from the guild bank to activate temporary (12 hour) combat stat multipliers for all members.
- **Common Perk**: Costs **100,000 coins**, gives **+5%** HP/ATK/DEF/SPD.
- **Rare Perk**: Costs **250,000 coins**, gives **+10%** HP/ATK/DEF/SPD.

The perks overwrite each other, meaning a rare perk replaces an active common perk (but resets the duration to 12 hours).

## Banners

### Banner prices

| Banner | Price |
|---|---:|
| `banner1` | 5,000 |
| `banner2` | 8,000 |
| `banner3` | 12,000 |
| `banner4` | 20,000 |
| `banner5` | 30,000 |
| `banner6` | 40,000 |
| `banner7` | 50,000 |
| `banner8` | 60,000 |
| `banner9` | 70,000 |
| `banner10` | 80,000 |
| `banner11` | 90,000 |
| `banner12` | 100,000 |
| `banner13` | 110,000 |
| `banner14` | 120,000 |
| `banner15` | 130,000 |
| `banner16` | 150,000 |

Banner purchases are paid by the **leader's personal coins**, not guild bank funds.

## Database / Storage Details

### Core guild tables
- `guilds`
- `guild_members`
- `guild_invites`
- `guild_raid_history`
- `guild_achievements`
- `guild_daily_raid_limits`
- `guild_pair_daily_rewards`
- `guild_banners_owned`
- `guild_raid_locks`

### Guild boss tables
- `guild_boss`
- `guild_boss_damage`
- `guild_boss_guild_damage`

### Important guild fields
- `guilds.bank_coins`
- `guilds.raid_points`
- `guilds.season_points`
- `guilds.weekly_points`
- `guilds.banner_id`
- `guilds.last_raid_at`
- `guilds.max_members`
- `guilds.war_wins`
- `guilds.war_losses`

## Strategic Tips / Balance Notes
- Raid with a full or near-full active roster when possible, because merged team size directly affects your raid power.
- Guild wars reward leaderboard prestige, while guild raids are the main direct bank-income PvP tool.
- Leader withdrawals should be planned carefully because floor division can waste small remainders.
- Guild boss rewards are damage-rank based for guilds, so regular coordinated attacks matter even if your guild is unlikely to land the final blow.
- Guild bosses despawn after 4 hours if not killed, so timing coordinated attacks is crucial.
- Use `.guild boss` to check boss status and time remaining before despawn.
- There is no chat command to disband a populated guild: the leader must reduce membership first, then leave.