# `gamesrn-tw-opponent-defenses` — version 1

The JSON that feeds the **Opponent** page (`/TW/opponent/`): every squad the opponent has revealed in one Territory War.
The format is source-neutral. Today it is produced from HotUtils; a future Discord bot reading the game posts the same shape.

| Endpoint | What it does |
|---|---|
| `POST /api/tw-opponent/upload` | Officers. Body = this JSON (or the raw HotUtils TW overview, converted on the server). No validate step: a good upload is live at once. Errors → HTTP 422 `{ ok:false, errors, warnings }`. Returns `{ ok, id, replaced, summary, warnings, enrich, url }`. |
| `GET /api/tw-opponent` | Board list, newest first. |
| `GET /api/tw-opponent?id=<id \| latest>` | One board: `board` (this JSON), `rosters` (game fill-in), `checks` (squad-GP check), plus `logs` (attacks logged per squad). |
| `POST /api/tw-opponent/enrich` | Officers. `{ id, force }` — read the opponent's rosters from the game again. |

**The war** is `guild` + `twDate`. Uploading again for the same war replaces the board (new zones, defeated squads) and keeps the game fill-in.
If `twDateFrom` is `"snapshot"`, the server uses the TW date of that guild's Defense Plan from the previous six days, so both pages share a war.

## Top level

| Key | Type | Required | Notes |
|---|---|---|---|
| `format` | string | ✔ | Exactly `"gamesrn-tw-opponent-defenses"`. |
| `version` | number | ✔ | `1`. |
| `source` | object | | `{ provider, endpoint, snapshotAt, capturedBy, statsNote }`. `provider` = `"hotutils"`, `"gamesrn-bot"`, … |
| `guild` | `{ id, name }` | ✔ | Our guild (Comlink guild id). |
| `opponent` | `{ id, name }` | ✔ | Their guild. The **id** is what lets the server read their rosters from the game. |
| `twDate` | `YYYY-MM-DD` | ✔ | |
| `twDateFrom` | `"given"` \| `"snapshot"` | | `"snapshot"` = the date was only taken from the snapshot time (see above). |
| `phase`, `score` | string, `{ us, them }` | | |
| `zones` | array | | `{ zone, type, status, open, revealed, squadsTotal, squadsDefeated, capacity }` — all ten are filled in by the server. |
| `squads` | array | ✔ | See below. |

Zone numbers are **HotUtils'** (as on the Defense Plan): Z1/Z2 front, Z3/Z4, Z5 (fleet)/Z6/Z7, Z8 (fleet)/Z9/Z10 back.

## `squads[]`

| Key | Notes |
|---|---|
| `id` | Optional. Default `"<zone>.<player-slug>.<LEAD>"` — stable across uploads, so logged attacks stay attached. |
| `zone`, `order` | `"Z1"`…`"Z10"`; order within the zone. |
| `player` | Opponent's in-game name (required). `allyCode`, `playerId` optional — a bot can send them; HotUtils can't. |
| `kind` | `"squad"` or `"fleet"` (default from the zone). |
| `lead` | Leader / capital ship base id; moved to the front of `units`. |
| `team` | Label (e.g. "Queen Amidala"). |
| `power` | Squad power as the source reports it — used for the GP check. |
| `defeated`, `successfulDefends`, `preloaded` | Status. |
| `units` | Up to 5 (squad) or 8 (fleet). See below. |
| `datacron` | `null` (none) or the object below. Ignored on fleets. |

### `units[]`

`{ baseId, name, level, stars, gear, relic, zetaCount, omicronCount, killed, healthPercent, stats }`

- `stats`: `{ speed, health, protection, damage, defense, potency, tenacity }` — as modded. Mods themselves are not carried.
- Optional, for a source that knows them: `zetas: [{ id, name }]`, `omicrons: [{ id, name, zone }]`, `ultimate`, `gp`.

### `datacron`

```json
{ "set": 36, "setName": "The Legend Codex", "level": 9, "focused": false, "character": "Rey",
  "stats": [ { "stat": "Offense", "value": 50, "rolls": 3 } ],
  "l3": { "id": "…", "label": "Light Side", "text": "…", "unit": null },
  "l6": { "id": "…", "label": "Resistance", "text": "…", "unit": null },
  "l9": { "id": "…", "label": "Rey", "text": "…", "unit": "GLREY" },
  "tiers": [ { "l": 1, "kind": "stat", "label": "Potency", "value": "+23.13%", "id": null } ] }
```

`l12` / `l15` follow the same shape. `stats[].value` is a percent number. `tiers` is the per-level roll list.

## `ourDefense[]` — our own squads as placed (optional)

What each of our members actually placed, so the Attack tab never suggests a unit or datacron that is on defense. When it is present it replaces the Defense Plan as the "on defense" list for My matchups; a later upload for the same war that leaves it out keeps the list from the earlier one (defenses are fixed at the lock).

`{ zone, player, allyCode, kind, units: [baseId, …], datacron: { id, set, level, focused, l3, l6, l9, … } }`

- `allyCode` if the source knows it; otherwise the member is matched by in-game `player` name against their TW lock file.
- `units` — base ids (strings) or `{ baseId }` objects, leader first.
- `datacron.id` — the game's datacron id if the source has it. Without it the datacron is identified from the member's lock inventory by set, level and ability ids, when exactly one fits; otherwise it is reported on My matchups as not identified (the units are still held back).
- From HotUtils this is the overview's `friendly.zones[].placements`, converted by `fromHotutils` (raw overview uploads get it too).

## Rosters are fixed at the first upload (2026-11-22)

The attack phase reads opponent rosters **only from the uploaded file**. The first upload of a war (the file taken at the start of the TW) sets every revealed squad's units — level, stars, gear, relic, zeta/omicron counts or names, stats — plus its `power` and `datacron`. A later upload for the same war (same `guild` + `twDate`, same opponent) brings **status only**: `defeated`, `successfulDefends`, `preloaded`, each unit's `killed` and `healthPercent`, zone counts, the score, and squads revealed for the first time (those take their details from the upload that first shows them). Each squad carries `detailsAt` (the snapshot its details came from); `source.lockSnapshotAt` is the first upload's snapshot time. Logic: `keepLockDetails` in `lib/tw-opponent.mjs`.

Nothing is read from the game any more: `POST /enrich` returns 410, uploads no longer start the Comlink fill-in, and the board's `rosters` / `checks` come back empty. (The old fill-in — `tw-opponent-enrich-background` — matched players by name and read their *current* accounts.)

## Validation

**Errors (nothing is saved):** bad JSON; wrong `format`/`version`; missing guild, opponent or `twDate`; `squads` not a list or over 600; a squad with a zone outside Z1–Z10, no player, no units, or too many units.

**Warnings (saved anyway):** a unit listed twice; a fleet in a ground zone (or the reverse); a base id the site doesn't know; an upload with no squads.

## Producing it from HotUtils

Step by step: `scripts/tw-war-file/README.md`. `node scripts/tw-war-file/snippet.mjs --twDate <date>` prints browser code for a `tw.hotutils.com/assets/` tab that reads the overview, converts it with `fromHotutils` (`netlify/functions/lib/tw-opponent.mjs`) and downloads the war file; `scripts/tw-war-file/convert.mjs` does the same for a saved raw overview. The upload box also accepts the raw overview and converts it on the server.

HotUtils' overview (checked 2026-11-21) has the same placement fields on both sides and **no ally codes and no datacron ids**, so `ourDefense` is matched by player name and its datacrons by set, level, ability ids and stat values.

## Dead marks (shared)

`POST /api/tw-opponent/mark` `{ id, squad, dead?, dead_units? }` — any member can mark a squad dead (`dead: true`) or mark some of its units dead (`dead_units: [baseId]`); everyone sees it. Only officers can undo (`dead: false`, or a shorter `dead_units`). Table `tw_opponent_marks`.

- `dead: true` → dead for everyone · `false` → an officer brought it back · `null` → follow the upload's `defeated`.
- A squad whose units are all marked dead is dead.
- A logged **win** against a board squad marks it dead automatically; a logged **loss** marks the defenders it killed.
- A newer upload that shows a squad defeated overrides an older officer "bring back".
- `GET ?id=` returns the board with marks applied: `squads[].defeated`, `units[].killed`, plus `reported` (what the upload said) and `marked: { dead, units, by, at }`.

## My matchups

`GET /api/tw-opponent?id=<board>&mine=<ally>` → the member's side: `roster` (units and datacrons at the TW lock), `defenseUnits` / `defenseCrons` (placed by this war's Defense Plan — never suggested), `holds` (offense holds — preferred) and `usage`.

`POST /api/tw-opponent/usage` `{ id, ally, units: { BASEID: "used" | "unavailable" | null }, datacrons: { id: … } }` — merged into `tw_offense_usage`; `null` makes it available again. Logging an attack marks the squad and datacron used.

The suggestions themselves are computed in the browser by `match.js` (`TWMatch.suggest`, rules in its header comment; tests in `tests/tw-match.test.mjs`): only counters already in the TW Counters database, only units the member still has, best matchup first, each unit and datacron once. A squad that has lost units is scored against what is left.

## Logged attacks

"Log my attack" on a squad saves a result in the TW Counters database with `opp_ref = { board, squad, player, zone }` (column `tw_counter_attempts.opp_ref`), the defenders' gear/relic/abilities and datacron as faced, and the attacker's units and datacron from their TW lock.
Defenders that were already down are saved in `def_state.dead`; the result then counts as an attack on a damaged squad (a retry), not a fresh win or loss, in the counter's record.
