Coverage for src/romfarmer/config/models.py: 74%

401 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-09-05 02:19 -0700

1"""Pydantic models for configuration validation. 

2 

3Note: Default paths are intentionally set to None or relative paths. 

4Use romfarmer.core.paths.PathResolver for runtime path resolution. 

5""" 

6 

7import contextvars 

8from enum import Enum 

9from pathlib import Path 

10from typing import Any, Literal 

11 

12from pydantic import BaseModel, Field, field_validator, model_validator 

13 

14 

15class DATSource(str, Enum): 

16 """DAT file source types.""" 

17 

18 NONE = "none" # No DAT — digital-only platforms (WiiWare, etc.) 

19 RETOOL_1G1R_ENG = "retool_1g1r_eng" 

20 RETOOL_1G1R_ALL = "retool_1g1r_all" 

21 RETOOL_1G1R_USA = "retool_1g1r_usa" 

22 NOINTRO_STANDARD = "nointro_standard" 

23 REDUMP_STANDARD = "redump_standard" 

24 REDUMP_RETOOL_1G1R_ENG = "redump_retool_1g1r_eng" # Redump with Retool filtering 

25 REDUMP_RETOOL_1G1R_USA = "redump_retool_1g1r_usa" 

26 MANUAL_SCAN = "manual_scan" # For PS3, etc. 

27 # Arcade sources 

28 MAME_OFFICIAL = "mame_official" # MAME official DAT 

29 MAME = "mame" # Filter from MAME DAT by driver 

30 FBNEO_OFFICIAL = "fbneo_official" # FBNeo official DAT 

31 HBMAME_OFFICIAL = "hbmame_official" # HBMAME official DAT 

32 

33 

34class OrganizationStyle(str, Enum): 

35 """Organization styles for different targets.""" 

36 

37 RICH = "rich" # Batocera: deep subdirs, full metadata 

38 BALANCED = "balanced" # RocknIX: alphabetical grouping 

39 MINIMAL = "minimal" # Everdrive: sort2folders with 50 file limit 

40 FLAT = "flat" # No organization, all files in one directory 

41 

42 

43class CompressionFormat(str, Enum): 

44 """Supported compression formats.""" 

45 

46 NONE = "none" # Loose files (for real hardware/Everdrive) 

47 ZIP = "zip" 

48 SEVENZ = "7z" 

49 CHD = "chd" 

50 CSO = "cso" 

51 XISO = "xiso" 

52 RVZ = "rvz" 

53 SQUASHFS = "sqfs" 

54 JB = "jb" # PS3 decrypted folder 

55 GZIP = "gzip" # PS3 ISO compression for ps3netsrv 

56 

57 

58class ExtractionType(str, Enum): 

59 """Types of content to extract from archives.""" 

60 

61 NONE = "none" # Don't extract, keep archives as-is 

62 CARTRIDGE = "cartridge" # Extract ROM files (.nes, .vb, .smd, etc.) 

63 DISC = "disc" # Extract disc images (CUE/BIN, ISO) 

64 RVZ = "rvz" # Unzip RVZ archives (Wii/GameCube) 

65 WUX = "wux" # Unzip WUX archives (Wii U) 

66 PS3 = "ps3" # Decrypt and extract PS3 ISO to JB folder format 

67 XISO = "xiso" # Convert Redump ISO to XISO format (Xbox/Xbox 360) 

68 MIXED = "mixed" # Platform has both cartridge and disc games 

69 

70 

71class PatternType(str, Enum): 

72 """Pattern matching types for selection filters.""" 

73 

74 GLOB = "glob" # Shell-style wildcards (*.USA*, [A-M]*) 

75 REGEX = "regex" # Full regex support 

76 

77 

78class SelectionStrategy(str, Enum): 

79 """Strategies for selecting files in selection filters.""" 

80 

81 FIRST = "first" # First N files (after sorting) 

82 LAST = "last" # Last N files (after sorting) 

83 RANDOM = "random" # Random N files 

84 LARGEST = "largest" # N largest files by size 

85 SMALLEST = "smallest" # N smallest files by size 

86 ALPHABETICAL = "alphabetical" # First N alphabetically 

87 RATING_BUDGET = "rating_budget" # Quality-based with size budget 

88 

89 

90# Backward compatibility alias 

91ScopeStrategy = SelectionStrategy 

92 

93 

94class SelectionSortBy(str, Enum): 

95 """Sort criteria for selection filters.""" 

96 

97 NAME = "name" # Sort by filename 

98 SIZE = "size" # Sort by file size 

99 MODIFIED = "modified" # Sort by modification time 

100 

101 

102# Backward compatibility alias 

103ScopeSortBy = SelectionSortBy 

104 

105 

106class SelectionPattern(BaseModel): 

107 """Pattern configuration for selection filters.""" 

108 

109 type: PatternType = Field(default=PatternType.GLOB, description="Pattern matching type") 

110 value: str = Field(description="Pattern to match against filenames") 

111 

112 

113# Backward compatibility alias 

114ScopePattern = SelectionPattern 

115 

116 

117class SelectionSort(BaseModel): 

118 """Sort configuration for selection filters.""" 

119 

120 by: SelectionSortBy = Field(default=SelectionSortBy.NAME, description="What to sort by") 

121 order: str = Field(default="asc", description="Sort order: asc or desc") 

122 

123 

124# Backward compatibility alias for SelectionSort 

125ScopeSort = SelectionSort 

126 

127 

128class SelectionConfig(BaseModel): 

129 """Selection filter configuration for choosing which ROMs to include.""" 

130 

131 name: str | None = Field( 

132 None, description="Selection configuration name (for referenced configs)" 

133 ) 

134 description: str | None = Field(None, description="Human-readable description") 

135 

136 # Strategy and limits 

137 strategy: SelectionStrategy = Field( 

138 default=SelectionStrategy.FIRST, description="Selection strategy" 

139 ) 

140 limit: int | None = Field(None, description="Maximum number of games to select", gt=0) 

141 percentage: float | None = Field( 

142 None, description="Select percentage of games (e.g., 20 for first 20%)", gt=0, le=100 

143 ) 

144 offset: float | None = Field( 

145 None, 

146 description="Skip this percentage before selecting (for phased builds, e.g., offset=20 skips first 20%)", 

147 ge=0, 

148 lt=100, 

149 ) 

150 

151 # Pattern filtering (optional, applied before strategy) 

152 pattern: SelectionPattern | None = Field(None, description="Pattern to filter filenames") 

153 

154 # Metadata-based exclusions 

155 exclude_hidden: bool = Field( 

156 default=False, description="Exclude games marked as hidden in EmulationStation metadata" 

157 ) 

158 exclude_unrated: bool = Field( 

159 default=False, description="Exclude games with no rating (rating = 0.0 or NULL)" 

160 ) 

161 exclude_demos: bool = Field( 

162 default=False, description="Exclude demos, betas, protos, samples (filename-based)" 

163 ) 

164 

165 # Region preferences for 1G1R and region pass (highest priority first) 

166 # e.g. ["USA", "World", "Europe", "Japan"] 

167 preferred_regions: list[str] = Field( 

168 default_factory=list, 

169 description="Region preferences in priority order (highest first). " 

170 "Consumed by the 1G1R and region planner passes.", 

171 ) 

172 

173 # Rating budget options (for RATING_BUDGET strategy) 

174 max_size_gb: float | None = Field( 

175 None, description="Maximum total size in GB (for rating_budget strategy)", gt=0 

176 ) 

177 min_rating: float | None = Field( 

178 None, 

179 description="Minimum rating threshold 0.0-1.0 (for rating_budget strategy)", 

180 ge=0.0, 

181 le=1.0, 

182 ) 

183 top_n: int | None = Field(None, description="Keep at most the N highest-rated games", ge=1) 

184 unrated: Literal["keep", "drop"] = Field( 

185 "keep", 

186 description="Rating pass: what to do with unrated games when min_rating is set", 

187 ) 

188 unrated_as: str = Field( 

189 "median", 

190 description="Budget pass: rank unrated games as 'median' (of rated games, per platform), " 

191 "'worst', 'best', or a 0.0-1.0 float", 

192 ) 

193 safety_margin: float = Field( 

194 0.0, 

195 description="Retired (2026-09-03): fixed headroom fraction. The aggregate p90 headroom in " 

196 "PlanSummary is the constraint. Kept for legacy configs that set it explicitly.", 

197 ge=0.0, 

198 lt=1.0, 

199 ) 

200 

201 # Sorting (optional) 

202 sort: SelectionSort | None = Field( 

203 None, description="Sort configuration before applying strategy" 

204 ) 

205 

206 # Random seed (for reproducible RANDOM strategy) 

207 seed: int | None = Field( 

208 None, description="Random seed for reproducible RANDOM strategy selection" 

209 ) 

210 

211 

212# Backward compatibility alias 

213ScopeConfig = SelectionConfig 

214 

215 

216class SystemType(str, Enum): 

217 """System complexity types - DEPRECATED, use extraction config instead.""" 

218 

219 SIMPLE = "simple" # No-Intro ZIPs, no extraction 

220 MEDIUM = "medium" # Redump, extraction + compression 

221 COMPLEX = "complex" # Multi-disc, special handling 

222 VERY_COMPLEX = "very_complex" # PS3, Xbox 360 DLC, etc. 

223 

224 

225class DATConfig(BaseModel): 

226 """DAT file configuration.""" 

227 

228 source: DATSource = Field(description="DAT source type (retool preferred)") 

229 file: Path | None = Field(None, description="Explicit DAT file path (overrides source)") 

230 expected_count: int | None = Field(None, description="Expected game count for validation") 

231 match_method: str = Field( 

232 "hash", 

233 description="Match method: 'hash' (default, exact MD5), 'fuzzy_name' (fallback to name matching when hash fails)", 

234 ) 

235 filter_driver: str | None = Field( 

236 None, description="MAME driver name to filter by (e.g., 'naomi', 'model2')" 

237 ) 

238 filter_romof: str | None = Field( 

239 None, description="MAME romof/BIOS to filter by (e.g., 'naomi2' for Naomi 2 games)" 

240 ) 

241 exclude_romof: list[str] | None = Field( 

242 None, 

243 description="Exclude games with these BIOS dependencies (e.g., ['naomi2'] to exclude Naomi 2 from Naomi)", 

244 ) 

245 name_pattern: str | None = Field( 

246 None, 

247 description="Glob pattern to filter game names (e.g., '*SGB Enhanced*' for Super Game Boy games)", 

248 ) 

249 exclude_name_pattern: str | None = Field( 

250 None, 

251 description="Glob pattern to exclude game names (e.g., '*SGB Enhanced*' to exclude Super Game Boy games from base set)", 

252 ) 

253 

254 @field_validator("file") 

255 @classmethod 

256 def validate_file_exists(cls, v: Path | None) -> Path | None: 

257 """Validate DAT file exists if specified.""" 

258 if v is not None and not v.exists(): 

259 raise ValueError(f"DAT file not found: {v}") 

260 return v 

261 

262 

263# Load-time switch for SourceConfig's path-exists check (see load_slim_platform). 

264CHECK_SOURCE_PATHS: contextvars.ContextVar[bool] = contextvars.ContextVar( 

265 "romfarmer_check_source_paths", default=True 

266) 

267 

268 

269class SourceConfig(BaseModel): 

270 """Source ROM configuration.""" 

271 

272 path: Path | None = Field(None, description="Source directory path (absolute)") 

273 root: str | None = Field(None, description="Source root ID (from sources.yaml)") 

274 subdir: str | None = Field(None, description="Subdirectory relative to root") 

275 type: str = Field("myrient", description="Source type (myrient, custom, etc.)") 

276 recursive: bool = Field(True, description="Scan subdirectories") 

277 

278 @model_validator(mode="after") 

279 def validate_path_or_root(self): 

280 """Ensure either path or root+subdir is specified.""" 

281 if not self.path and not self.root: 

282 raise ValueError("Either 'path' or 'root' must be specified for source") 

283 

284 # If path is specified, it must exist — unless the loader says the paths 

285 # are not going to be used (a Spec supplies its own sources; the bare- 

286 # environment gate must not need this host's mounts). 

287 if self.path and CHECK_SOURCE_PATHS.get() and not self.path.exists(): 

288 # We allow non-existent paths if we are going to resolve them later via root? 

289 # No, Pydantic validation happens at load time. 

290 # If we use 'root', 'path' will be None initially, so this check is fine. 

291 # But if 'path' is provided, it should exist. 

292 raise ValueError(f"Source path not found: {self.path}") 

293 

294 return self 

295 

296 

297class ListFileConfig(BaseModel): 

298 """List file configuration.""" 

299 

300 directory: Path = Field(description="Directory containing list files") 

301 patterns: dict[str, str] = Field( 

302 default={ 

303 "delete": "{system}-delete", 

304 "add_myrient": "{system}+*", 

305 "add_extra": "{system}.*", 

306 }, 

307 description="List file naming patterns", 

308 ) 

309 

310 @field_validator("directory") 

311 @classmethod 

312 def validate_directory_exists(cls, v: Path) -> Path: 

313 """Validate list directory exists.""" 

314 if not v.exists(): 

315 raise ValueError(f"List directory not found: {v}") 

316 return v 

317 

318 

319class OrganizationConfig(BaseModel): 

320 """Organization configuration.""" 

321 

322 style: OrganizationStyle = Field(description="Organization style") 

323 max_files_per_group: int | None = Field(50, description="Max files per group for MINIMAL style") 

324 create_subdirs: bool = Field(True, description="Create subdirectories for list files") 

325 subdir_prefix: str | None = Field(None, description="Prefix for subdirectories (e.g., '_')") 

326 

327 

328class CompressionConfig(BaseModel): 

329 """Compression configuration.""" 

330 

331 format: CompressionFormat = Field(description="Target compression format") 

332 tool: str | None = Field(None, description="Compression tool path") 

333 parameters: dict[str, Any] = Field(default_factory=dict, description="Tool-specific parameters") 

334 verify: bool = Field(True, description="Verify compressed files") 

335 

336 

337class ExtractionConfig(BaseModel): 

338 """Extraction configuration for archives and disc images.""" 

339 

340 enabled: bool = Field(default=False, description="Enable extraction") 

341 type: ExtractionType = Field( 

342 default=ExtractionType.NONE, description="Type of content to extract" 

343 ) 

344 # PS3-specific settings 

345 keys_directory: Path | None = Field(None, description="PS3 disc keys directory") 

346 ps3dec_path: Path | None = Field(None, description="Path to PS3Dec tool") 

347 # Xbox XISO settings 

348 extract_xiso_path: Path | None = Field(None, description="Path to extract-xiso tool") 

349 

350 

351class PS3UpdatesConfig(BaseModel): 

352 """PS3 updates configuration.""" 

353 

354 enabled: bool = Field(default=True, description="Apply official game updates") 

355 nps_database: Path | None = Field( 

356 default=None, description="NoPayStation database path (PS3_DLCS.tsv)" 

357 ) 

358 pkg_archive: Path | None = Field(default=None, description="PKG archive directory") 

359 use_sony_psn: bool = Field(default=True, description="Also check Sony PSN cache for updates") 

360 

361 

362class PS3DLCMode(str, Enum): 

363 """PS3 DLC handling modes.""" 

364 

365 NONE = "none" # Don't process DLC 

366 EXTRACT = "extract" # Extract and merge DLC into disc (for real PS3) 

367 COPY = "copy" # Copy PKG files to _PKG folder (for RPCS3) 

368 

369 

370class PS3DLCConfig(BaseModel): 

371 """PS3 DLC configuration.""" 

372 

373 enabled: bool = Field(default=False, description="Enable DLC processing") 

374 mode: PS3DLCMode = Field( 

375 default=PS3DLCMode.COPY, 

376 description="DLC handling mode: extract (merge to disc) or copy (PKG to _PKG folder)", 

377 ) 

378 

379 

380class RatingFilterConfig(BaseModel): 

381 """Rating-based filtering configuration.""" 

382 

383 enabled: bool = Field(False, description="Enable rating-based filtering") 

384 top_n: int | None = Field(None, description="Keep only top N highest-rated games") 

385 max_size_gb: float | None = Field( 

386 None, description="Keep top-rated games that fit within size budget (GB)" 

387 ) 

388 min_rating: float | None = Field(None, description="Minimum rating threshold (0.0-1.0)") 

389 

390 @model_validator(mode="after") 

391 def validate_filter_criteria(self): 

392 """Ensure at least one filter criterion is specified if enabled.""" 

393 if self.enabled: 

394 if not any([self.top_n, self.max_size_gb, self.min_rating]): 

395 raise ValueError( 

396 "At least one filter criterion (top_n, max_size_gb, min_rating) " 

397 "must be specified when rating_filter is enabled" 

398 ) 

399 return self 

400 

401 

402class GenerationFilterConfig(BaseModel): 

403 """Cross-platform generation deduplication configuration. 

404 

405 Implements "1 Game 1 Generation" (1G1Gen) filtering for disc-based systems. 

406 When enabled, games that appear on multiple platforms in the same console 

407 generation will be deduplicated based on platform priority. 

408 

409 Example Gen 6 (PS2 > GameCube > Xbox): 

410 - Grand Theft Auto: Vice City exists on all three platforms 

411 - Result: Keep PS2 version, remove GameCube and Xbox versions 

412 - Lower priority platforms become "exclusives only" 

413 

414 Configuration: 

415 generation_filter: 

416 enabled: true 

417 generation: gen6 # Use gen5, gen6, gen7, or gen4cd 

418 

419 Output folders will be named like: output/gen6-dedupe-batocera/ 

420 """ 

421 

422 enabled: bool = Field(False, description="Enable cross-platform generation deduplication") 

423 generation: str = Field(description="Generation identifier (gen5, gen6, gen7, gen4cd)") 

424 rescue_lists: dict[str, list[str]] | None = Field( 

425 None, description="Platform -> list of game names to protect from removal" 

426 ) 

427 

428 @field_validator("generation") 

429 @classmethod 

430 def validate_generation(cls, v: str) -> str: 

431 """Validate generation identifier.""" 

432 valid_generations = ["gen4cd", "gen5", "gen6", "gen7"] 

433 if v not in valid_generations: 

434 raise ValueError( 

435 f"Invalid generation '{v}'. Must be one of: {', '.join(valid_generations)}" 

436 ) 

437 return v 

438 

439 

440class TargetProfile(BaseModel): 

441 """Target system profile (Batocera, RocknIX, Everdrive).""" 

442 

443 name: str = Field(description="Profile name") 

444 output_path: Path = Field(description="Output directory") 

445 organization: OrganizationConfig = Field(description="Organization configuration") 

446 compression: CompressionConfig | None = Field( 

447 None, description="Compression override for this target" 

448 ) 

449 metadata: bool = Field(True, description="Generate metadata (gamelist.xml)") 

450 enabled: bool = Field(True, description="Enable this target") 

451 

452 # Removed strict parent directory validation to allow for dynamic path generation 

453 # where the parent directory might not exist yet. 

454 

455 

456class MetadataFilterConfig(BaseModel): 

457 """Metadata-driven ROM filter configuration. 

458 

459 Runs after DAT matching (once MD5s are known) and drops or keeps ROMs 

460 based on their ``scraped_games`` database entry. All conditions are 

461 ANDed together — a ROM must pass every active condition to survive. 

462 

463 Typical uses:: 

464 

465 # Strip nongames + hidden entries from every build 

466 metadata_filter: 

467 exclude_nongames: true 

468 exclude_hidden: true 

469 

470 # Shoot-em-up target — keep only matching genres 

471 metadata_filter: 

472 include_genres: 

473 - "Shoot'em Up" 

474 - "Shoot'em Up / Vertical" 

475 - "Shoot'em Up / Horizontal" 

476 - "Shooter" 

477 require_metadata: false # keep unscraped ROMs too 

478 

479 # Quality cut 

480 metadata_filter: 

481 min_rating: 0.7 

482 exclude_nongames: true 

483 """ 

484 

485 # --- Name-based --- 

486 exclude_nongames: bool = Field( 

487 default=False, 

488 description="Exclude entries whose scraped name starts with 'ZZZ' (ARRM nongame marker)", 

489 ) 

490 exclude_name_patterns: list[str] = Field( 

491 default_factory=list, 

492 description=( 

493 "Glob patterns matched against the scraped game name. " 

494 "Any match → exclude. E.g. ['ZZZ*', '*[BIOS]*']" 

495 ), 

496 ) 

497 

498 # --- Genre --- 

499 include_genres: list[str] = Field( 

500 default_factory=list, 

501 description=( 

502 "Whitelist of genre substrings. A ROM is kept if its scraped genre " 

503 "contains ANY of these strings (case-insensitive). " 

504 "ROMs with no genre are kept unless require_metadata=True." 

505 ), 

506 ) 

507 exclude_genres: list[str] = Field( 

508 default_factory=list, 

509 description=( 

510 "Blacklist of genre substrings. A ROM is excluded if its scraped genre " 

511 "contains ANY of these strings (case-insensitive)." 

512 ), 

513 ) 

514 

515 # --- Rating --- 

516 min_rating: float | None = Field( 

517 default=None, 

518 description="Minimum ScreenScraper rating (0.0–1.0). ROMs below this are excluded.", 

519 ge=0.0, 

520 le=1.0, 

521 ) 

522 

523 # --- Players --- 

524 min_players: int | None = Field( 

525 default=None, 

526 description=( 

527 "Minimum player count. E.g. min_players=2 keeps only multiplayer games. " 

528 "Parsed from scraped 'players' field ('1', '1-2', '1-4', '4+', ...)." 

529 ), 

530 ge=1, 

531 ) 

532 

533 # --- Flags --- 

534 exclude_hidden: bool = Field( 

535 default=False, 

536 description="Exclude ROMs whose scraped_games.hidden flag is set.", 

537 ) 

538 

539 # --- Metadata presence --- 

540 require_metadata: bool = Field( 

541 default=False, 

542 description=( 

543 "When True, ROMs with no scraped_games entry are excluded. " 

544 "When False (default), unscraped ROMs always pass through." 

545 ), 

546 ) 

547 has_metadata: bool = Field( 

548 default=False, 

549 description=( 

550 "When True, only include ROMs that have a scraped_games entry. " 

551 "Alias for require_metadata=True (more readable in configs)." 

552 ), 

553 ) 

554 

555 @model_validator(mode="after") 

556 def sync_has_metadata(self) -> "MetadataFilterConfig": 

557 """has_metadata=True implies require_metadata=True.""" 

558 if self.has_metadata: 

559 self.require_metadata = True 

560 return self 

561 

562 

563class PlatformConfig(BaseModel): 

564 """Configuration for a single platform (NES, Saturn, etc.).""" 

565 

566 name: str = Field(description="Platform name") 

567 type: str | None = Field( 

568 None, description="Platform type: 'arcade' for arcade systems, None for consoles" 

569 ) 

570 emulator: str | None = Field( 

571 None, description="Emulator name (e.g., 'fbneo', 'mame', 'flycast')" 

572 ) 

573 metadata_system: str | None = Field( 

574 None, 

575 description="System name to use for metadata lookups (defaults to platform name). " 

576 "Useful for platforms that share ROMs (e.g., Sega arcade platforms use 'mame')", 

577 ) 

578 system_type: SystemType | None = Field( 

579 None, description="System complexity type (DEPRECATED - use extraction config)" 

580 ) 

581 dat: DATConfig | None = Field(None, description="DAT configuration") 

582 sources: list[SourceConfig] = Field(description="Source ROM locations") 

583 chd_sources: list[SourceConfig] | None = Field( 

584 None, description="CHD source locations (arcade platforms)" 

585 ) 

586 arcade_filter: dict[str, Any] | None = Field( 

587 None, description="Arcade-specific filter configuration" 

588 ) 

589 lists: ListFileConfig | None = Field(None, description="List file configuration") 

590 extraction: ExtractionConfig = Field( 

591 default_factory=lambda: ExtractionConfig(enabled=False, type=ExtractionType.NONE), 

592 description="Extraction configuration", 

593 ) 

594 updates: PS3UpdatesConfig | None = Field(None, description="PS3 updates configuration") 

595 dlc: PS3DLCConfig | None = Field(None, description="PS3 DLC configuration") 

596 selection: SelectionConfig | None = Field( 

597 None, description="Selection filter configuration (replaces rating_filter)" 

598 ) 

599 metadata_filter: MetadataFilterConfig | None = Field( 

600 None, description="Metadata-driven filter (genre, rating, players, nongames, etc.)" 

601 ) 

602 rating_filter: RatingFilterConfig = Field( 

603 default_factory=lambda: RatingFilterConfig(enabled=False), 

604 description="Rating-based filtering configuration (DEPRECATED - use selection instead)", 

605 ) 

606 compression: CompressionConfig | None = Field( 

607 None, description="Default compression for this platform" 

608 ) 

609 targets: list[TargetProfile] = Field(description="Output targets") 

610 enabled: bool = Field(True, description="Enable this platform") 

611 

612 # Legacy settings - kept for backward compatibility 

613 extract_archives: bool | None = Field( 

614 None, description="DEPRECATED: Use extraction.enabled instead" 

615 ) 

616 multi_disc_handling: bool = Field(False, description="Enable multi-disc detection") 

617 custom_stages: list[str] = Field(default_factory=list, description="Custom stage names") 

618 

619 @model_validator(mode="after") 

620 def validate_platform_config(self) -> "PlatformConfig": 

621 """Validate platform configuration consistency.""" 

622 import warnings 

623 

624 # Track if user explicitly set extraction.enabled 

625 user_set_extraction = self.extraction.enabled or self.extraction.type != ExtractionType.NONE 

626 

627 # Deprecation warning for system_type 

628 if self.system_type is not None: 

629 warnings.warn( 

630 f"Platform '{self.name}': 'system_type' is deprecated. " 

631 "Use 'extraction' config instead. See docs for migration guide.", 

632 DeprecationWarning, 

633 stacklevel=2, 

634 ) 

635 

636 # Migrate legacy extract_archives to new extraction config 

637 if self.extract_archives is not None: 

638 warnings.warn( 

639 f"Platform '{self.name}': 'extract_archives' is deprecated. " 

640 "Use 'extraction.enabled' instead.", 

641 DeprecationWarning, 

642 stacklevel=2, 

643 ) 

644 self.extraction.enabled = self.extract_archives 

645 user_set_extraction = True # User explicitly set via legacy field 

646 

647 # Auto-detect extraction type from system_type only if not explicitly set 

648 if self.system_type is not None and not user_set_extraction: 

649 if self.system_type == SystemType.SIMPLE: 

650 self.extraction.enabled = False 

651 elif self.system_type == SystemType.COMPLEX: 

652 # COMPLEX systems (Wii/GameCube) use RVZ extraction 

653 self.extraction.enabled = True 

654 self.extraction.type = ExtractionType.RVZ 

655 elif self.system_type == SystemType.VERY_COMPLEX: 

656 # VERY_COMPLEX systems like PS3 

657 self.extraction.enabled = True 

658 self.extraction.type = ExtractionType.PS3 

659 elif self.system_type == SystemType.MEDIUM: 

660 self.extraction.enabled = True 

661 # Try to infer type from compression format 

662 if self.compression and self.compression.format == CompressionFormat.CHD: 

663 self.extraction.type = ExtractionType.DISC 

664 else: 

665 # Default to cartridge if extracting but not CHD 

666 self.extraction.type = ExtractionType.CARTRIDGE 

667 

668 # If user set extraction.enabled but no type, try to infer from system_type or compression 

669 if self.extraction.enabled and self.extraction.type == ExtractionType.NONE: 

670 if self.system_type == SystemType.COMPLEX: 

671 self.extraction.type = ExtractionType.RVZ 

672 elif self.system_type == SystemType.VERY_COMPLEX: 

673 self.extraction.type = ExtractionType.PS3 

674 elif self.compression and self.compression.format == CompressionFormat.CHD: 

675 self.extraction.type = ExtractionType.DISC 

676 else: 

677 self.extraction.type = ExtractionType.CARTRIDGE 

678 

679 return self 

680 

681 

682class BuildType(str, Enum): 

683 """Build types for different use cases.""" 

684 

685 TARGET = "target" # Multi-system build for a target (frontend + device) 

686 SYSTEM = "system" # Single platform build 

687 LEGACY = "legacy" # Old-style build (for backwards compatibility during migration) 

688 

689 

690class TierStrategy(str, Enum): 

691 """Selection strategy for platform tiers.""" 

692 

693 ALWAYS_INCLUDE = "always_include" # Include entire 1G1R set 

694 BEST_OF = "best_of" # Use best-of list only 

695 BEST_OF_EXTENDED = "best_of_extended" # Best-of + notable games 

696 SKIP = "skip" # Don't include this tier 

697 

698 

699class TierDefinition(BaseModel): 

700 """Definition of a single platform tier.""" 

701 

702 description: str = "" 

703 default_strategy: TierStrategy = TierStrategy.ALWAYS_INCLUDE 

704 estimated_total_mb: int | None = None # For Tier 1/2 (total) 

705 estimated_per_platform_mb: int | None = None # For Tier 3+ (per platform) 

706 platforms: list[str] = Field(default_factory=list) 

707 

708 

709class AllocationRules(BaseModel): 

710 """Rules for allocating storage budget across tiers.""" 

711 

712 guaranteed_tiers: list[int] = Field(default_factory=lambda: [1, 2]) 

713 guaranteed_reserve_percent: int = 10 

714 tier_3_threshold_gb: int = 64 

715 tier_3_max_percent: int = 40 

716 tier_4_threshold_gb: int = 128 

717 tier_4_max_percent: int = 30 

718 tier_5_threshold_gb: int = 500 

719 tier_5_max_percent: int = 50 

720 

721 

722class StorageProfile(BaseModel): 

723 """Pre-defined storage profile for common scenarios.""" 

724 

725 description: str = "" 

726 max_tier: int = 5 

727 tier_3_strategy: TierStrategy = TierStrategy.BEST_OF 

728 tier_4_strategy: TierStrategy = TierStrategy.BEST_OF 

729 tier_5_strategy: TierStrategy = TierStrategy.SKIP 

730 

731 @field_validator("tier_3_strategy", "tier_4_strategy", "tier_5_strategy", mode="before") 

732 @classmethod 

733 def validate_strategy(cls, v): 

734 """Convert string to TierStrategy enum.""" 

735 if isinstance(v, str): 

736 return TierStrategy(v) 

737 return v 

738 

739 

740class PlatformTiersConfig(BaseModel): 

741 """Platform tier system configuration. 

742 

743 Defines storage priority for platforms when building space-constrained targets. 

744 Loaded from config/platform_tiers.yaml. 

745 """ 

746 

747 tier_1: TierDefinition = Field(default_factory=TierDefinition) 

748 tier_2: TierDefinition = Field(default_factory=TierDefinition) 

749 tier_3: TierDefinition = Field(default_factory=TierDefinition) 

750 tier_4: TierDefinition = Field(default_factory=TierDefinition) 

751 tier_5: TierDefinition = Field(default_factory=TierDefinition) 

752 allocation_rules: AllocationRules = Field(default_factory=AllocationRules) 

753 profiles: dict[str, StorageProfile] = Field(default_factory=dict) 

754 

755 def get_tier(self, tier_num: int) -> TierDefinition: 

756 """Get tier definition by number.""" 

757 tier_map = { 

758 1: self.tier_1, 

759 2: self.tier_2, 

760 3: self.tier_3, 

761 4: self.tier_4, 

762 5: self.tier_5, 

763 } 

764 return tier_map.get(tier_num, TierDefinition()) 

765 

766 def get_platform_tier(self, platform: str) -> int | None: 

767 """Get the tier number for a platform. 

768 

769 Returns: 

770 Tier number (1-5) or None if platform not in any tier 

771 """ 

772 for tier_num in range(1, 6): 

773 tier = self.get_tier(tier_num) 

774 if platform in tier.platforms: 

775 return tier_num 

776 return None 

777 

778 def get_profile(self, profile_name: str) -> StorageProfile | None: 

779 """Get a storage profile by name.""" 

780 return self.profiles.get(profile_name) 

781 

782 def get_strategy_for_tier( 

783 self, tier_num: int, profile: StorageProfile | None = None 

784 ) -> TierStrategy: 

785 """Get the selection strategy for a tier. 

786 

787 Args: 

788 tier_num: Tier number (1-5) 

789 profile: Optional storage profile to override defaults 

790 

791 Returns: 

792 TierStrategy for the tier 

793 """ 

794 if profile: 

795 # Profile overrides for tiers 3-5 

796 if tier_num == 3: 

797 return profile.tier_3_strategy 

798 elif tier_num == 4: 

799 return profile.tier_4_strategy 

800 elif tier_num == 5: 

801 return profile.tier_5_strategy 

802 # Tiers 1-2 always use always_include 

803 return TierStrategy.ALWAYS_INCLUDE 

804 

805 # Use tier's default strategy 

806 return self.get_tier(tier_num).default_strategy 

807 

808 

809class BuildConfig(BaseModel): 

810 """Master build configuration (e.g., rocknix-512gb.yaml). 

811 

812 Supports two build modes: 

813 

814 1. TARGET BUILD (type: target) 

815 - Builds multiple platforms for a specific target (frontend + device) 

816 - Output folder: {frontend}-{device}-{storage}-{profile}/ 

817 - Example: rocknix-r36s-512gb-complete/ 

818 

819 2. SYSTEM BUILD (type: system) 

820 - Builds a single platform with specific settings 

821 - Output folder: {platform}-{compression}-{selection}/ 

822 - Example: saturn-chd-all/ 

823 

824 Also supports nested orchestration via the 'includes' field for complex builds. 

825 

826 Example (Target Build): 

827 name: r36s-complete 

828 type: target 

829 target: rocknix-r36s 

830 storage_budget: 512gb 

831 profile: complete 

832 platforms: all 

833 

834 Example (System Build): 

835 name: saturn-chd-all 

836 type: system 

837 platform: saturn 

838 compression: chd 

839 selection: all 

840 

841 Example (Legacy Build - backwards compatible): 

842 name: 1tb-batocera 

843 includes: 

844 - nointro-1g1r-eng-7z-batocera 

845 - redump-1g1r-eng-chd-batocera 

846 excludes: 

847 - 3ds 

848 platforms: [] 

849 """ 

850 

851 name: str = Field(description="Build name") 

852 description: str | None = Field(None, description="Build description") 

853 version: str | None = Field(None, description="Build version") 

854 

855 # ═══════════════════════════════════════════════════════════════════════════ 

856 # NEW: Build type and target configuration 

857 # ═══════════════════════════════════════════════════════════════════════════ 

858 build_type: BuildType | None = Field( 

859 default=None, 

860 description="Build type: 'target' (multi-system), 'system' (single platform), or None (legacy)", 

861 ) 

862 target: str | None = Field( 

863 default=None, 

864 description="Target name for target builds (e.g., 'rocknix-r36s', 'batocera-pc')", 

865 ) 

866 storage_budget: str | None = Field( 

867 default=None, description="Storage budget (e.g., '512gb', '1tb', 'unlimited')" 

868 ) 

869 profile: str | None = Field( 

870 default=None, 

871 description="Build profile name for output folder (e.g., 'complete', 'test-10games', 'favorites')", 

872 ) 

873 platform_budgets: dict[str, str] = Field( 

874 default_factory=dict, 

875 description="Per-platform storage budgets (e.g., {'psx': '80gb', '3ds': '50gb'})", 

876 ) 

877 

878 # For system builds (single platform) 

879 platform: str | None = Field( 

880 default=None, description="Single platform for system builds (e.g., 'saturn')" 

881 ) 

882 compression: str | None = Field( 

883 default=None, description="Compression format for system builds (e.g., 'chd', 'zip', '7z')" 

884 ) 

885 selection: str | None = Field( 

886 default=None, 

887 description="Selection name for system builds (e.g., 'all', 'japanese', 'top30')", 

888 ) 

889 

890 # Selection override for special builds (e.g., test builds with 10 games per system) 

891 selection_override: SelectionConfig | None = Field( 

892 default=None, 

893 description="Override selection for all platforms (e.g., limit to 10 games for testing)", 

894 ) 

895 

896 # Generation-based cross-platform deduplication (1G1Gen) 

897 generation_filter: GenerationFilterConfig | None = Field( 

898 default=None, description="Cross-platform generation deduplication configuration (1G1Gen)" 

899 ) 

900 

901 # ═══════════════════════════════════════════════════════════════════════════ 

902 # Legacy fields (still supported for backwards compatibility) 

903 # ═══════════════════════════════════════════════════════════════════════════ 

904 includes: list[str] = Field( 

905 default_factory=list, 

906 description="Other orchestration configs to include (processed before platforms)", 

907 ) 

908 excludes: list[str] = Field( 

909 default_factory=list, 

910 description="Platforms to exclude from the final build (applied after includes)", 

911 ) 

912 platforms: list[str] = Field( 

913 default_factory=list, 

914 description="Platform config files to include (in addition to includes)", 

915 ) 

916 global_dat_priority: list[DATSource] = Field( 

917 default=[ 

918 DATSource.RETOOL_1G1R_ENG, 

919 DATSource.RETOOL_1G1R_USA, 

920 DATSource.NOINTRO_STANDARD, 

921 DATSource.REDUMP_STANDARD, 

922 ], 

923 description="Global DAT source priority", 

924 ) 

925 global_lists: ListFileConfig | None = Field(None, description="Global list file configuration") 

926 workspace: Path | None = Field( 

927 None, 

928 description="Workspace root directory (auto-detected if not set)", 

929 ) 

930 dat_directory: Path | None = Field( 

931 None, description="DAT files directory (defaults to workspace/dats)" 

932 ) 

933 checkpoint_enabled: bool = Field(True, description="Enable checkpointing for resume") 

934 parallel_platforms: bool = Field(False, description="Process platforms in parallel") 

935 max_workers: int = Field(4, description="Max parallel workers") 

936 

937 # Added fields for flexibility 

938 settings: dict[str, Any] = Field(default_factory=dict, description="Build execution settings") 

939 storage: dict[str, Any] = Field(default_factory=dict, description="Storage paths configuration") 

940 platform_overrides: dict[str, Any] = Field( 

941 default_factory=dict, description="Platform-specific overrides" 

942 ) 

943 

944 # Post-build hooks - commands to run after all platforms complete 

945 post_build: list[dict[str, Any]] = Field( 

946 default_factory=list, 

947 description="Commands to run after build completes (e.g., jdupes for deduplication)", 

948 ) 

949 

950 # Deployment configuration 

951 deploy: dict[str, Any] | None = Field( 

952 None, description="Deployment configuration (rsync to target device)" 

953 ) 

954 

955 @field_validator("workspace", "dat_directory", mode="before") 

956 @classmethod 

957 def validate_directory_exists(cls, v: Path | None) -> Path | None: 

958 """Validate directory exists if specified.""" 

959 if v is not None and not Path(v).exists(): 

960 raise ValueError(f"Directory not found: {v}") 

961 return v 

962 

963 @model_validator(mode="after") 

964 def validate_has_content(self): 

965 """Validate build configuration based on build type.""" 

966 # Determine build type if not explicitly set 

967 if self.build_type is None: 

968 if self.target is not None: 

969 # Has target = target build 

970 object.__setattr__(self, "build_type", BuildType.TARGET) 

971 elif self.platform is not None and self.compression is not None: 

972 # Has single platform + compression = system build 

973 object.__setattr__(self, "build_type", BuildType.SYSTEM) 

974 elif self.includes or self.platforms: 

975 # Has includes/platforms = legacy build 

976 object.__setattr__(self, "build_type", BuildType.LEGACY) 

977 

978 # Validate based on build type 

979 if self.build_type == BuildType.TARGET: 

980 if not self.target: 

981 raise ValueError("Target builds require 'target' field") 

982 if not self.profile: 

983 raise ValueError("Target builds require 'profile' field") 

984 # storage_budget defaults to 'unlimited' if not specified 

985 if not self.storage_budget: 

986 object.__setattr__(self, "storage_budget", "unlimited") 

987 

988 elif self.build_type == BuildType.SYSTEM: 

989 if not self.platform: 

990 raise ValueError("System builds require 'platform' field") 

991 if not self.compression: 

992 raise ValueError("System builds require 'compression' field") 

993 # selection defaults to 'all' if not specified 

994 if not self.selection: 

995 object.__setattr__(self, "selection", "all") 

996 

997 elif self.build_type == BuildType.LEGACY or self.build_type is None: 

998 # Legacy validation: must have includes or platforms 

999 if not self.includes and not self.platforms: 

1000 raise ValueError( 

1001 "Legacy builds require at least one of 'includes' or 'platforms'. " 

1002 "Or specify 'target' for a target build, or 'platform' + 'compression' for a system build." 

1003 ) 

1004 

1005 return self 

1006 

1007 def get_output_folder_name(self) -> str: 

1008 """Generate the output folder name based on build type. 

1009 

1010 Returns: 

1011 Output folder name string 

1012 """ 

1013 if self.build_type == BuildType.TARGET: 

1014 # Will be computed with composed target: {frontend}-{device}-{storage}-{profile} 

1015 # For now, return a placeholder that will be resolved later 

1016 return f"{self.target}-{self.storage_budget}-{self.profile}" 

1017 

1018 elif self.build_type == BuildType.SYSTEM: 

1019 return f"{self.platform}-{self.compression}-{self.selection}" 

1020 

1021 else: 

1022 # Legacy: use the build name 

1023 return self.name 

1024 

1025 def is_target_build(self) -> bool: 

1026 """Check if this is a target build.""" 

1027 return self.build_type == BuildType.TARGET 

1028 

1029 def is_system_build(self) -> bool: 

1030 """Check if this is a system build.""" 

1031 return self.build_type == BuildType.SYSTEM 

1032 

1033 def is_legacy_build(self) -> bool: 

1034 """Check if this is a legacy build.""" 

1035 return self.build_type == BuildType.LEGACY or self.build_type is None