Add version groups to share routes and boss battles across games

Routes and boss battles now belong to a version_group instead of
individual games, so paired versions (e.g. Red/Blue, Gold/Silver)
share the same route structure and boss battles. Route encounters
gain a game_id column to support game-specific encounter tables
within a shared route. Includes migration, updated seeds, API
changes, and frontend type updates.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-02-08 12:07:42 +01:00
parent 979f57f184
commit 3e88ba50fa
22 changed files with 631 additions and 161 deletions

View File

@@ -9,27 +9,65 @@ from app.models.game import Game
from app.models.pokemon import Pokemon
from app.models.route import Route
from app.models.route_encounter import RouteEncounter
from app.models.version_group import VersionGroup
async def upsert_games(session: AsyncSession, games: list[dict]) -> dict[str, int]:
"""Upsert game records, return {slug: id} mapping."""
for game in games:
stmt = insert(Game).values(
name=game["name"],
slug=game["slug"],
generation=game["generation"],
region=game["region"],
release_year=game.get("release_year"),
color=game.get("color"),
async def upsert_version_groups(
session: AsyncSession,
vg_data: dict[str, dict],
) -> dict[str, int]:
"""Upsert version group records, return {slug: id} mapping."""
for vg_slug, vg_info in vg_data.items():
vg_name = " / ".join(
g["name"].replace("Pokemon ", "")
for g in vg_info["games"].values()
)
stmt = insert(VersionGroup).values(
name=vg_name,
slug=vg_slug,
).on_conflict_do_update(
index_elements=["slug"],
set_={
"name": game["name"],
"generation": game["generation"],
"region": game["region"],
"release_year": game.get("release_year"),
"color": game.get("color"),
},
set_={"name": vg_name},
)
await session.execute(stmt)
await session.flush()
result = await session.execute(select(VersionGroup.slug, VersionGroup.id))
return {row.slug: row.id for row in result}
async def upsert_games(
session: AsyncSession,
games: list[dict],
slug_to_vg_id: dict[str, int] | None = None,
) -> dict[str, int]:
"""Upsert game records, return {slug: id} mapping."""
for game in games:
values = {
"name": game["name"],
"slug": game["slug"],
"generation": game["generation"],
"region": game["region"],
"release_year": game.get("release_year"),
"color": game.get("color"),
}
update_set = {
"name": game["name"],
"generation": game["generation"],
"region": game["region"],
"release_year": game.get("release_year"),
"color": game.get("color"),
}
if slug_to_vg_id is not None:
vg_id = slug_to_vg_id.get(game["slug"])
if vg_id is not None:
values["version_group_id"] = vg_id
update_set["version_group_id"] = vg_id
stmt = insert(Game).values(**values).on_conflict_do_update(
index_elements=["slug"],
set_=update_set,
)
await session.execute(stmt)
@@ -67,10 +105,10 @@ async def upsert_pokemon(session: AsyncSession, pokemon_list: list[dict]) -> dic
async def upsert_routes(
session: AsyncSession,
game_id: int,
version_group_id: int,
routes: list[dict],
) -> dict[str, int]:
"""Upsert route records for a game, return {name: id} mapping.
"""Upsert route records for a version group, return {name: id} mapping.
Handles hierarchical routes: routes with 'children' are parent routes,
and their children get parent_route_id set accordingly.
@@ -79,11 +117,11 @@ async def upsert_routes(
for route in routes:
stmt = insert(Route).values(
name=route["name"],
game_id=game_id,
version_group_id=version_group_id,
order=route["order"],
parent_route_id=None, # Parent routes have no parent
).on_conflict_do_update(
constraint="uq_routes_game_name",
constraint="uq_routes_version_group_name",
set_={"order": route["order"], "parent_route_id": None},
)
await session.execute(stmt)
@@ -92,7 +130,7 @@ async def upsert_routes(
# Get mapping of parent routes
result = await session.execute(
select(Route.name, Route.id).where(Route.game_id == game_id)
select(Route.name, Route.id).where(Route.version_group_id == version_group_id)
)
name_to_id = {row.name: row.id for row in result}
@@ -106,12 +144,12 @@ async def upsert_routes(
for child in children:
stmt = insert(Route).values(
name=child["name"],
game_id=game_id,
version_group_id=version_group_id,
order=child["order"],
parent_route_id=parent_id,
pinwheel_zone=child.get("pinwheel_zone"),
).on_conflict_do_update(
constraint="uq_routes_game_name",
constraint="uq_routes_version_group_name",
set_={
"order": child["order"],
"parent_route_id": parent_id,
@@ -124,7 +162,7 @@ async def upsert_routes(
# Return full mapping including children
result = await session.execute(
select(Route.name, Route.id).where(Route.game_id == game_id)
select(Route.name, Route.id).where(Route.version_group_id == version_group_id)
)
return {row.name: row.id for row in result}
@@ -134,8 +172,9 @@ async def upsert_route_encounters(
route_id: int,
encounters: list[dict],
dex_to_id: dict[int, int],
game_id: int,
) -> int:
"""Upsert encounters for a route, return count of upserted rows."""
"""Upsert encounters for a route and game, return count of upserted rows."""
count = 0
for enc in encounters:
pokemon_id = dex_to_id.get(enc["pokeapi_id"])
@@ -146,12 +185,13 @@ async def upsert_route_encounters(
stmt = insert(RouteEncounter).values(
route_id=route_id,
pokemon_id=pokemon_id,
game_id=game_id,
encounter_method=enc["method"],
encounter_rate=enc["encounter_rate"],
min_level=enc["min_level"],
max_level=enc["max_level"],
).on_conflict_do_update(
constraint="uq_route_pokemon_method",
constraint="uq_route_pokemon_method_game",
set_={
"encounter_rate": enc["encounter_rate"],
"min_level": enc["min_level"],

View File

@@ -11,40 +11,21 @@ from app.models.game import Game
from app.models.pokemon import Pokemon
from app.models.route import Route
from app.models.route_encounter import RouteEncounter
from app.models.version_group import VersionGroup
from app.seeds.loader import (
upsert_evolutions,
upsert_games,
upsert_pokemon,
upsert_route_encounters,
upsert_routes,
upsert_version_groups,
)
DATA_DIR = Path(__file__).parent / "data"
# All Gen 1-9 games
GAME_FILES = [
# Gen 1
"red", "blue", "yellow",
# Gen 2
"gold", "silver", "crystal",
# Gen 3
"ruby", "sapphire", "emerald", "firered", "leafgreen",
# Gen 4
"diamond", "pearl", "platinum", "heartgold", "soulsilver",
# Gen 5
"black", "white", "black-2", "white-2",
# Gen 6
"x", "y", "omega-ruby", "alpha-sapphire",
# Gen 7
"sun", "moon", "ultra-sun", "ultra-moon", "lets-go-pikachu", "lets-go-eevee",
# Gen 8
"sword", "shield", "brilliant-diamond", "shining-pearl", "legends-arceus",
# Gen 9
"scarlet", "violet", "legends-z-a",
]
VG_JSON = Path(__file__).parent / "version_groups.json"
def load_json(filename: str) -> list[dict]:
def load_json(filename: str):
path = DATA_DIR / filename
with open(path) as f:
return json.load(f)
@@ -56,64 +37,99 @@ async def seed():
async with async_session() as session:
async with session.begin():
# 1. Upsert games
# 1. Upsert version groups
with open(VG_JSON) as f:
vg_data = json.load(f)
vg_slug_to_id = await upsert_version_groups(session, vg_data)
print(f"Version Groups: {len(vg_slug_to_id)} upserted")
# Build game_slug -> vg_id mapping
game_slug_to_vg_id: dict[str, int] = {}
for vg_slug, vg_info in vg_data.items():
vg_id = vg_slug_to_id[vg_slug]
for game_slug in vg_info["games"]:
game_slug_to_vg_id[game_slug] = vg_id
# 2. Upsert games (with version_group_id)
games_data = load_json("games.json")
slug_to_id = await upsert_games(session, games_data)
slug_to_id = await upsert_games(session, games_data, game_slug_to_vg_id)
print(f"Games: {len(slug_to_id)} upserted")
# 2. Upsert Pokemon
# 3. Upsert Pokemon
pokemon_data = load_json("pokemon.json")
dex_to_id = await upsert_pokemon(session, pokemon_data)
print(f"Pokemon: {len(dex_to_id)} upserted")
# 3. Per game: upsert routes and encounters
# 4. Per version group: upsert routes once, then encounters per game
total_routes = 0
total_encounters = 0
for game_slug in GAME_FILES:
game_id = slug_to_id.get(game_slug)
if game_id is None:
print(f"Warning: game '{game_slug}' not found, skipping")
for vg_slug, vg_info in vg_data.items():
vg_id = vg_slug_to_id[vg_slug]
game_slugs = list(vg_info["games"].keys())
# Use the first game's route JSON for the shared route structure
first_game_slug = game_slugs[0]
routes_file = DATA_DIR / f"{first_game_slug}.json"
if not routes_file.exists():
print(f" {vg_slug}: no route data ({first_game_slug}.json), skipping")
continue
routes_data = load_json(f"{game_slug}.json")
routes_data = load_json(f"{first_game_slug}.json")
if not routes_data:
print(f" {game_slug}: no route data, skipping")
print(f" {vg_slug}: empty route data, skipping")
continue
route_map = await upsert_routes(session, game_id, routes_data)
total_routes += len(route_map)
for route in routes_data:
route_id = route_map.get(route["name"])
if route_id is None:
print(f" Warning: route '{route['name']}' not found")
# Upsert routes once per version group
route_map = await upsert_routes(session, vg_id, routes_data)
total_routes += len(route_map)
print(f" {vg_slug}: {len(route_map)} routes")
# Upsert encounters per game (each game may have different encounters)
for game_slug in game_slugs:
game_id = slug_to_id.get(game_slug)
if game_id is None:
print(f" Warning: game '{game_slug}' not found, skipping")
continue
# Parent routes may have empty encounters
if route["encounters"]:
enc_count = await upsert_route_encounters(
session, route_id, route["encounters"], dex_to_id
)
total_encounters += enc_count
game_routes_file = DATA_DIR / f"{game_slug}.json"
if not game_routes_file.exists():
continue
# Handle child routes
for child in route.get("children", []):
child_id = route_map.get(child["name"])
if child_id is None:
print(f" Warning: child route '{child['name']}' not found")
game_routes_data = load_json(f"{game_slug}.json")
for route in game_routes_data:
route_id = route_map.get(route["name"])
if route_id is None:
print(f" Warning: route '{route['name']}' not found")
continue
enc_count = await upsert_route_encounters(
session, child_id, child["encounters"], dex_to_id
)
total_encounters += enc_count
# Parent routes may have empty encounters
if route["encounters"]:
enc_count = await upsert_route_encounters(
session, route_id, route["encounters"],
dex_to_id, game_id,
)
total_encounters += enc_count
print(f" {game_slug}: {len(route_map)} routes")
# Handle child routes
for child in route.get("children", []):
child_id = route_map.get(child["name"])
if child_id is None:
print(f" Warning: child route '{child['name']}' not found")
continue
enc_count = await upsert_route_encounters(
session, child_id, child["encounters"],
dex_to_id, game_id,
)
total_encounters += enc_count
print(f" {game_slug}: encounters loaded")
print(f"\nTotal routes: {total_routes}")
print(f"Total encounters: {total_encounters}")
# 4. Upsert evolutions
# 5. Upsert evolutions
evolutions_path = DATA_DIR / "evolutions.json"
if evolutions_path.exists():
evolutions_data = load_json("evolutions.json")
@@ -131,32 +147,33 @@ async def verify():
async with async_session() as session:
# Overall counts
vg_count = (await session.execute(select(func.count(VersionGroup.id)))).scalar()
games_count = (await session.execute(select(func.count(Game.id)))).scalar()
pokemon_count = (await session.execute(select(func.count(Pokemon.id)))).scalar()
routes_count = (await session.execute(select(func.count(Route.id)))).scalar()
enc_count = (await session.execute(select(func.count(RouteEncounter.id)))).scalar()
print(f"Version Groups: {vg_count}")
print(f"Games: {games_count}")
print(f"Pokemon: {pokemon_count}")
print(f"Routes: {routes_count}")
print(f"Route Encounters: {enc_count}")
# Per-game breakdown
# Per-version-group route counts
result = await session.execute(
select(Game.name, func.count(Route.id))
.join(Route, Route.game_id == Game.id)
.group_by(Game.name)
.order_by(Game.name)
select(VersionGroup.slug, func.count(Route.id))
.join(Route, Route.version_group_id == VersionGroup.id)
.group_by(VersionGroup.slug)
.order_by(VersionGroup.slug)
)
print("\nRoutes per game:")
print("\nRoutes per version group:")
for row in result:
print(f" {row[0]}: {row[1]}")
# Per-game encounter counts
result = await session.execute(
select(Game.name, func.count(RouteEncounter.id))
.join(Route, Route.game_id == Game.id)
.join(RouteEncounter, RouteEncounter.route_id == Route.id)
.join(RouteEncounter, RouteEncounter.game_id == Game.id)
.group_by(Game.name)
.order_by(Game.name)
)