# GuildHelper v3 Rebuild Blueprint

## Executive summary
The v2 addon has valuable features, but the implementation is tightly coupled, duplicated across files, and hard to maintain. A full rewrite is the recommended path for v3.

GuildHelper v3 is a clean replacement, not an upgrade path. The old addon should be uninstalled and v3 should stand entirely on its own with a new database, new UI, new sync model, and no legacy compatibility layer.

Why rewrite instead of patching:
- Core functions are duplicated or redefined in multiple files (`CreateInterface`, `ShowPane`, `CreateDataSyncPane`, `AddLogEntry`).
- Message/data architecture is split across overlapping modules (`DataSyncManager`, `DataSyncHandler`, workflow/event logic).
- UI panes for content boards are mostly copy/paste variants (`NewsPane`, `InfoPane`, `CalendarPane`).
- Chat feature is deeply intertwined with setup and event handling and should be removed cleanly.

## What v2 currently does well
- Broad feature set: roster, member profile, announcements/info/calendar content, groups, setup, maintenance, sync.
- Uses shared data model with metadata for sync candidates.
- Has basic minimap launcher and pane navigation.
- Supports federated guild concept and cross-guild filtering.

## High-impact v2 issues to fix in v3

### 1) Structural duplication and conflicts
- Same behaviors are implemented in multiple places with different logic.
- Example areas: interface bootstrap, pane switching, logging, and data sync UI.

Impact:
- Bug-prone behavior depending on load order.
- Hard to reason about ownership and side effects.

### 2) Inconsistent data shape and keying
- Roster/member code mixes field names (`pt_*`, `gb_*`, `data.*`) and ID strategies (array-style loops over map-like tables).
- Several panes iterate with `ipairs` while data is keyed by ID.

Impact:
- Lost updates, failed deletes, and silent data corruption risk.

### 3) Sync protocol fragility
- Chunking exists, but message types and control flow are spread across modules.
- No robust transaction model (session id, ack/nack, retry policy, checksum/hash validation).
- Sync completion advances table flow in multiple places, risking race/order bugs.

Impact:
- Intermittent sync failures and hard-to-debug desync.

### 4) UI redundancy and maintenance cost
- News, Info, and Calendar panes repeat almost identical CRUD table/editor patterns.
- Setup stores chat-related state (channel/password/color) that should be removed if chat is removed.

Impact:
- Every UX change requires edits in 3+ places.

### 5) Over-scoped setup and mixed responsibilities
- Setup pane handles federation, chat configuration, and color concerns together.
- Business logic lives in UI code.

Impact:
- Difficult to test and impossible to evolve safely.

## v3 product direction (aligned to your request)

### Remove
- Remove in-addon chat entirely.
- Remove chat channel join logic, chat pane, chat message encoding/decoding, and chat setup fields.

### Simplify
- Replace separate News + Info boards with one unified Content Board.
- Keep Calendar as a content type inside the same board system (or a dedicated view backed by same store).

### Improve
- Stronger sync engine with explicit protocol state.
- Cleaner data schema designed only for v3.
- Sleeker, modernized single-frame UI with reusable components.

## Finalized v3 feature scope

### Core features
- A completely new modern UI.
- A single messaging board instead of separate news/info boards.
- Detailed toon information stored directly in the roster dataset.
- A guild needs feature that recommends shortages such as tank, healer, DPS, ranged, and melee.
- Continued support for separate guild data and linked guild groups.
- Improved syncing between members in the same guild or linked guilds.
- Better maintenance for stale members, guild leavers, linked-guild cleanup, and deleted records.
- Continued support for personal group creation and quick invites for parties and raids.
- A cleaner v3 database built specifically for syncing and linked guild support.

### Explicit non-features
- No compatibility with the old addon.
- No migration or import from v2.
- No in-addon chat feature.

## Recommended v3 architecture

## Folder layout
```text
GuildHelper/
  GuildHelper.toc
  Core/
    Bootstrap.lua
    Events.lua
    Router.lua
    Logger.lua
    Schema.lua
  Data/
    Store.lua
    Repositories.lua
    Validators.lua
  Sync/
    Protocol.lua
    Transport.lua
    SessionManager.lua
    Reconciler.lua
  UI/
    MainFrame.lua
    Components/
      TableView.lua
      FormView.lua
      Modal.lua
      Toast.lua
    Views/
      DashboardView.lua
      RosterView.lua
      MemberView.lua
      ContentBoardView.lua
      GroupsView.lua
      SetupView.lua
      SyncView.lua
      MaintenanceView.lua
  Features/
    RosterService.lua
    ContentService.lua
    GroupsService.lua
    FederationService.lua
    NeedsService.lua
    MaintenanceService.lua
```

## Core principles
- Single source of truth in `Data/Store.lua`.
- UI only renders state and dispatches actions.
- Sync engine is isolated from UI.
- Every record has deterministic ID, `updatedAt`, `updatedBy`, `deleted`, and `revision`.
- Guild data remains separable while allowing linked guild views and sync permissions.
- No legacy translation layer or backward-compatibility code.

## Suggested v3 data model
```lua
GuildHelperDB = {
  schemaVersion = 1,
  profile = {
    minimap = {},
    ui = { framePos = nil, selectedView = "dashboard" }
  },
  guild = {
    federation = {
      homeGuild = nil,
      linkedGuilds = {},
      permissions = {}
    },
    roster = {},
    content = {},
    groups = {},
    needs = {
      rules = {
        raid = {
          tanks = 2,
          healers = 4,
          melee = 5,
          ranged = 7,
          dps = 12
        },
        party = {
          tanks = 1,
          healers = 1,
          melee = 1,
          ranged = 2,
          dps = 3
        }
      },
      snapshots = {}
    },
    maintenance = {
      exclusions = {},
      staleMembers = {},
      pendingDeletes = {}
    }
  },
  sync = {
    lastSyncAt = nil,
    peers = {},
    tableMeta = {
      roster = { checksum = "", updatedAt = "" },
      content = { checksum = "", updatedAt = "" },
      groups = { checksum = "", updatedAt = "" },
      federation = { checksum = "", updatedAt = "" }
    }
  }
}
```

### Record design

#### Roster records
- Keyed by full toon name.
- Store detailed fields directly on the roster record payload:
  - name, realm, guildName, class, spec, level, faction
  - primaryRole, secondaryRoles
  - meleeOrRanged
  - itemLevel
  - professions
  - interests
  - mainCharacter
  - rank
  - guildJoinDate
  - lastSeenAt
  - notes used by guild tools

#### Content records
- One unified board dataset.
- Types should start with:
  - `announcement`
  - `event`
  - `resource`

#### Group records
- Personal groups owned by a player.
- Members should reference roster IDs instead of raw duplicated strings where possible.

## Sync v3 design (better data sync)
- Prefix: keep one addon prefix, define explicit message envelope.
- Envelope fields:
  - `op` (HELLO, META_REQ, META_RES, DELTA_REQ, DELTA_RES, ACK, DONE, ERR)
  - `sessionId`
  - `table`
  - `seq`, `total`
  - `payload`
  - `crc` (optional checksum for chunk integrity)
- Session manager:
  - Start session, timeout, retry window, exponential backoff.
  - Exactly one in-flight session per peer.
- Reconciliation:
  - Compare checksums and per-record revisions.
  - Pull only missing/stale records.
  - Apply tombstones (`deleted = true`) with newer revision wins.
- Guild boundary rules:
  - Sync only with same-guild peers or explicitly linked guild peers.
  - Preserve guild ownership on records even when shown in linked-guild views.
  - Never flatten all guilds into one anonymous dataset.
- Observability:
  - Sync monitor UI showing peer, table, progress, retries, last error.

### Sync goals
- Reliable sync across same-guild and linked-guild members.
- Minimal unnecessary traffic by syncing per table and per revision.
- Safe cleanup of stale or deleted records without orphaning linked-guild data.
- Clear operator visibility when sync fails or a peer is outdated.

## UI/UX v3 direction (sleeker)
- Keep one main frame with left nav + right content, but reduce visual noise.
- Introduce reusable table component with sorting/filter/pagination once.
- Unify editors into one form component with schema-driven fields.
- Add compact dashboard cards:
  - Roster count (online/offline)
  - Upcoming events
  - Last sync status
  - Federation health
- Add guild needs cards:
  - Current role coverage
  - Missing roles by target composition
  - Suggested recruiting or invite focus
- Keep officer-only controls clearly separated by role.

### Recommended primary navigation
- Dashboard
- Board
- Roster
- Groups
- Sync
- Setup
- Maintenance

## Content model cleanup
- Replace all separate information boards with one `ContentBoardView`.
- Content type field controls behavior:
  - `announcement`
  - `event`
  - `resource`
- Same list/editor workflow, different form fields by type.
- Board filters should support guild, author, type, and pinned status.

## Guild needs feature
- Compute recommendations from active roster data.
- Start with rules-based recommendations, not heuristic guessing.
- Inputs should include:
  - primary role
  - secondary roles
  - melee vs ranged
  - active/inactive state
  - optionally online-only filtering for live group building
- Outputs should include:
  - shortages by role
  - shortages by damage profile
  - suggested members who can fill the gap
  - recruiting guidance for linked guild leadership

## Chat removal checklist
- Remove files/modules:
  - `Interface/ChatPane.lua`
  - `Modules/GuildChat.lua`
- Remove references and startup hooks:
  - Nav button for chat.
  - `JoinChatChannel` call on startup.
  - Chat-related setup fields (`chatchannel`, `channelpassword`, color legend purely for chat).
  - Chat-related event handling branches.

## Maintenance model
- Maintenance should work on the v3 database only.
- Detect and surface:
  - members no longer in the guild
  - members moved between linked guilds
  - stale records not updated within policy threshold
  - tombstoned records ready for purge
- Use soft deletion first, hard purge later through explicit maintenance actions.
- Provide officer-facing cleanup tools with filters and safe confirmations.

## Suggested implementation phases

### Phase 1: Foundation
- Bootstrap, saved vars schema, logger, router.
- Main frame shell + initial modern navigation.

### Phase 2: Data layer
- Store/repository services for roster/content/groups/federation/setup.
- Validation and helper utilities.

### Phase 3: Sync engine
- Protocol envelope, chunking, session manager, reconciler.
- Sync monitor view.

### Phase 4: Feature views
- Roster with detailed toon records.
- Content board.
- Guild needs dashboard.
- Groups + Maintenance + Setup.

### Phase 5: Polish and operations
- Slash commands and diagnostics.
- Officer workflows and permission polish.
- Sync hardening and cleanup UX.

## First concrete build tasks
1. Create v3 TOC and load order with only `Core/Bootstrap.lua` and `Core/Events.lua`.
2. Implement `GuildHelperDB` schema bootstrap with `schemaVersion = 1`.
3. Build `UI/MainFrame.lua` with nav routes but stub views.
4. Implement `Data/Store.lua` plus repositories for roster and content.
5. Implement `Features/NeedsService.lua` with rules-based role counts.
6. Implement `Sync/Protocol.lua` envelope and peer session flow.

## Recommendation
Proceed with a full rewrite for v3 as a standalone replacement addon. Remove chat, collapse redundant boards into one unified board, keep guild separation with linked guild support, add roster-driven guild-needs analysis, and build the database and sync model specifically for the new architecture.
