Coverage for src/romfarmer/cli/scores.py: 0%

146 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-09-01 23:08 -0700

1""" 

2CLI commands for fetching and querying external game scores. 

3 

4Usage 

5----- 

6 romfarmer scores fetch --platform ps2 

7 romfarmer scores fetch --all 

8 romfarmer scores show --platform ps2 --min-score 8.0 

9 romfarmer scores stats 

10 romfarmer scores lookup "Resident Evil 4" --platform ps2 

11""" 

12 

13import os 

14import sys 

15from pathlib import Path 

16 

17import click 

18from rich.console import Console 

19from rich.progress import BarColumn, Progress, SpinnerColumn, TaskProgressColumn, TextColumn 

20from rich.table import Table 

21 

22console = Console() 

23 

24DEFAULT_DB = "metadata/database/romfarmer.db" 

25 

26 

27@click.group("scores") 

28def scores_group() -> None: 

29 """Fetch and query external game scores (MobyGames, RAWG).""" 

30 

31 

32# --------------------------------------------------------------------------- 

33# fetch 

34# --------------------------------------------------------------------------- 

35 

36 

37@scores_group.command("fetch") 

38@click.option( 

39 "--platform", 

40 "-p", 

41 default=None, 

42 help="Platform to fetch (e.g. ps2, snes). Required unless --all is set.", 

43) 

44@click.option( 

45 "--all", 

46 "fetch_all", 

47 is_flag=True, 

48 default=False, 

49 help="Fetch scores for all supported platforms.", 

50) 

51@click.option( 

52 "--source", 

53 default="mobygames", 

54 type=click.Choice(["mobygames", "rawg"], case_sensitive=False), 

55 show_default=True, 

56 help="Score source to use.", 

57) 

58@click.option( 

59 "--api-key", 

60 envvar="MOBYGAMES_API_KEY", 

61 default=None, 

62 help="API key. Defaults to MOBYGAMES_API_KEY env var.", 

63) 

64@click.option( 

65 "--rate-limit", 

66 default=1.1, 

67 show_default=True, 

68 type=float, 

69 help=( 

70 "Seconds between API requests. " 

71 "Hobbyist tier = 720 req/hour hard limit. " 

72 "Use 5.0 for guaranteed no-429 (1 req/5s = exactly 720/hour). " 

73 "Default 1.1 is faster but may hit hourly quota; " 

74 "on 429 the client auto-waits until the next UTC :00 reset." 

75 ), 

76) 

77@click.option( 

78 "--db", 

79 "db_path", 

80 default=DEFAULT_DB, 

81 show_default=True, 

82 help="Path to romfarmer.db metadata database.", 

83) 

84@click.option( 

85 "--platforms", 

86 "platform_list", 

87 default=None, 

88 help="Comma-separated list of platforms to fetch (alternative to --all).", 

89) 

90def fetch_command( 

91 platform: str | None, 

92 fetch_all: bool, 

93 source: str, 

94 api_key: str | None, 

95 rate_limit: float, 

96 db_path: str, 

97 platform_list: str | None, 

98) -> None: 

99 """ 

100 Fetch game scores from an external source and store them in the DB. 

101 

102 \b 

103 Examples: 

104 romfarmer scores fetch --platform ps2 

105 romfarmer scores fetch --all --rate-limit 15 

106 romfarmer scores fetch --platforms ps2,ps3,psx 

107 MOBYGAMES_API_KEY=xxx romfarmer scores fetch --platform snes 

108 """ 

109 from romfarmer.metadata.database import MetadataDatabase 

110 from romfarmer.metadata.external_scores import ( 

111 MOBYGAMES_PLATFORM_IDS, 

112 RAWG_PLATFORM_IDS, 

113 MobyGamesFetcher, 

114 RawgFetcher, 

115 ) 

116 

117 # Determine target platforms 

118 if platform_list: 

119 targets = [p.strip() for p in platform_list.split(",") if p.strip()] 

120 elif platform: 

121 targets = [platform] 

122 elif fetch_all: 

123 platform_map = MOBYGAMES_PLATFORM_IDS if source == "mobygames" else RAWG_PLATFORM_IDS 

124 targets = list(platform_map.keys()) 

125 else: 

126 raise click.UsageError("Specify --platform <name>, --platforms <list>, or --all.") 

127 

128 db = MetadataDatabase(Path(db_path)) 

129 

130 if source == "mobygames": 

131 resolved_key = api_key or os.environ.get("MOBYGAMES_API_KEY", "") 

132 if not resolved_key: 

133 console.print( 

134 "[red]Error:[/red] MobyGames API key required.\n" 

135 " Pass [bold]--api-key KEY[/bold] or set " 

136 "[bold]MOBYGAMES_API_KEY[/bold] environment variable.\n" 

137 " Register at: https://www.mobygames.com/info/api/" 

138 ) 

139 sys.exit(1) 

140 fetcher = MobyGamesFetcher(db=db, api_key=resolved_key, rate_limit_seconds=rate_limit) 

141 else: 

142 resolved_key = api_key or os.environ.get("RAWG_API_KEY", "") 

143 if not resolved_key: 

144 console.print( 

145 "[red]Error:[/red] RAWG API key required.\n" 

146 " Pass [bold]--api-key KEY[/bold] or set " 

147 "[bold]RAWG_API_KEY[/bold] environment variable.\n" 

148 " Register at: https://rawg.io/apidocs" 

149 ) 

150 sys.exit(1) 

151 fetcher = RawgFetcher(db=db, api_key=resolved_key) 

152 

153 total_stored = 0 

154 errors: list[str] = [] 

155 

156 with Progress( 

157 SpinnerColumn(), 

158 TextColumn("[progress.description]{task.description}"), 

159 BarColumn(), 

160 TaskProgressColumn(), 

161 console=console, 

162 transient=False, 

163 ) as progress: 

164 outer_task = progress.add_task( 

165 f"[cyan]Fetching {source} scores...[/cyan]", 

166 total=len(targets), 

167 ) 

168 

169 for platform_name in targets: 

170 progress.update( 

171 outer_task, 

172 description=f"[cyan]{source}[/cyan] → [yellow]{platform_name}[/yellow]", 

173 ) 

174 

175 pages_done = [0] 

176 

177 def on_progress( 

178 fetched: int, 

179 stored: int, 

180 page: int, 

181 _platform: str = platform_name, 

182 _pages: list[int] = pages_done, 

183 ) -> None: 

184 _pages[0] = page 

185 progress.update( 

186 outer_task, 

187 description=( 

188 f"[cyan]{source}[/cyan] → [yellow]{_platform}[/yellow] " 

189 f"page {page} ({stored} stored)" 

190 ), 

191 ) 

192 

193 try: 

194 count = fetcher.fetch_platform(platform_name, progress_callback=on_progress) 

195 total_stored += count 

196 console.print( 

197 f" [green]✓[/green] {platform_name}: " 

198 f"[bold]{count}[/bold] games stored " 

199 f"({pages_done[0]} pages)" 

200 ) 

201 except ValueError as exc: 

202 console.print(f" [yellow]⚠[/yellow] {platform_name}: {exc}") 

203 errors.append(platform_name) 

204 except Exception as exc: 

205 console.print(f" [red]✗[/red] {platform_name}: {exc}") 

206 errors.append(platform_name) 

207 

208 progress.advance(outer_task) 

209 

210 console.print( 

211 f"\n[bold green]Done.[/bold green] Total stored: [bold]{total_stored}[/bold] game scores." 

212 ) 

213 if errors: 

214 console.print( 

215 f"[yellow]Skipped {len(errors)} platform(s) with errors: {', '.join(errors)}[/yellow]" 

216 ) 

217 

218 

219# --------------------------------------------------------------------------- 

220# show 

221# --------------------------------------------------------------------------- 

222 

223 

224@scores_group.command("show") 

225@click.option("--platform", "-p", required=True, help="Platform to show (e.g. ps2).") 

226@click.option( 

227 "--source", 

228 default=None, 

229 type=click.Choice(["mobygames", "rawg"], case_sensitive=False), 

230 help="Filter by source.", 

231) 

232@click.option( 

233 "--min-score", 

234 default=None, 

235 type=float, 

236 help="Minimum user score (0-10 scale).", 

237) 

238@click.option( 

239 "--min-critic", 

240 default=None, 

241 type=int, 

242 help="Minimum critic score (0-100 scale).", 

243) 

244@click.option("--limit", "-n", default=50, show_default=True, help="Max rows to display.") 

245@click.option("--db", "db_path", default=DEFAULT_DB, show_default=True) 

246def show_command( 

247 platform: str, 

248 source: str | None, 

249 min_score: float | None, 

250 min_critic: int | None, 

251 limit: int, 

252 db_path: str, 

253) -> None: 

254 """Show external scores for a platform.""" 

255 from romfarmer.metadata.database import MetadataDatabase 

256 

257 db = MetadataDatabase(Path(db_path)) 

258 scores = db.get_external_scores_for_platform( 

259 platform=platform, 

260 source=source, 

261 min_user_score=min_score, 

262 min_critic_score=min_critic, 

263 ) 

264 

265 if not scores: 

266 console.print( 

267 f"[yellow]No external scores found for '{platform}'.[/yellow] " 

268 f"Run [bold]romfarmer scores fetch --platform {platform}[/bold] first." 

269 ) 

270 return 

271 

272 table = Table(title=f"External Scores — {platform} ({len(scores)} games)") 

273 table.add_column("Title", style="cyan", max_width=50) 

274 table.add_column("User Score", justify="right") 

275 table.add_column("Critic", justify="right") 

276 table.add_column("Source", style="dim") 

277 

278 displayed = 0 

279 for s in scores: 

280 if displayed >= limit: 

281 break 

282 user = f"{s.user_score:.1f}/10" if s.user_score is not None else "—" 

283 critic = str(s.critic_score) if s.critic_score is not None else "—" 

284 table.add_row(s.title, user, critic, s.source) 

285 displayed += 1 

286 

287 console.print(table) 

288 if len(scores) > limit: 

289 console.print(f"[dim]... and {len(scores) - limit} more (use --limit to see more)[/dim]") 

290 

291 

292# --------------------------------------------------------------------------- 

293# stats 

294# --------------------------------------------------------------------------- 

295 

296 

297@scores_group.command("stats") 

298@click.option("--db", "db_path", default=DEFAULT_DB, show_default=True) 

299def stats_command(db_path: str) -> None: 

300 """Show coverage statistics for all fetched external scores.""" 

301 from romfarmer.metadata.database import MetadataDatabase 

302 

303 db = MetadataDatabase(Path(db_path)) 

304 rows = db.get_external_scores_stats() 

305 

306 if not rows: 

307 console.print( 

308 "[yellow]No external scores in DB yet.[/yellow] " 

309 "Run [bold]romfarmer scores fetch --all[/bold] to populate." 

310 ) 

311 return 

312 

313 table = Table(title="External Score Coverage") 

314 table.add_column("Platform", style="cyan") 

315 table.add_column("Source", style="dim") 

316 table.add_column("Games", justify="right") 

317 table.add_column("With User", justify="right") 

318 table.add_column("With Critic", justify="right") 

319 table.add_column("Avg User Score", justify="right") 

320 table.add_column("Last Fetched", style="dim") 

321 

322 for r in rows: 

323 last = r["last_fetch"].strftime("%Y-%m-%d") if r["last_fetch"] else "—" 

324 avg = f"{r['avg_user_score']:.2f}" if r["avg_user_score"] else "—" 

325 table.add_row( 

326 r["platform"], 

327 r["source"], 

328 str(r["count"]), 

329 str(r["with_user"]), 

330 str(r["with_critic"]), 

331 avg, 

332 last, 

333 ) 

334 

335 console.print(table) 

336 

337 

338# --------------------------------------------------------------------------- 

339# lookup 

340# --------------------------------------------------------------------------- 

341 

342 

343@scores_group.command("lookup") 

344@click.argument("title") 

345@click.option("--platform", "-p", required=True, help="Platform to search (e.g. ps2).") 

346@click.option("--db", "db_path", default=DEFAULT_DB, show_default=True) 

347def lookup_command(title: str, platform: str, db_path: str) -> None: 

348 """ 

349 Look up the external score for a game by title. 

350 

351 Uses the same normalized matching that the pipeline uses. 

352 

353 \b 

354 Examples: 

355 romfarmer scores lookup "Resident Evil 4" --platform ps2 

356 romfarmer scores lookup "Gran Turismo 3 (USA)" --platform ps2 

357 """ 

358 from romfarmer.metadata.database import MetadataDatabase 

359 from romfarmer.metadata.external_scores import normalize_title 

360 

361 db = MetadataDatabase(Path(db_path)) 

362 normalized = normalize_title(title) 

363 result = db.lookup_external_score(platform=platform, normalized_title=normalized) 

364 

365 console.print(f"[dim]Normalized query:[/dim] '{normalized}'") 

366 

367 if result is None: 

368 console.print( 

369 f"[yellow]No match found[/yellow] for '{title}' on {platform}.\n" 

370 "Try fetching scores first: " 

371 f"[bold]romfarmer scores fetch --platform {platform}[/bold]" 

372 ) 

373 return 

374 

375 user = f"{result.user_score:.1f}/10" if result.user_score is not None else "N/A" 

376 critic = f"{result.critic_score}/100" if result.critic_score is not None else "N/A" 

377 normalized_0_to_1 = result.best_score_normalized 

378 

379 table = Table(show_header=False) 

380 table.add_column("Field", style="dim") 

381 table.add_column("Value", style="cyan") 

382 table.add_row("Title", result.title) 

383 table.add_row("Platform", result.platform) 

384 table.add_row("User Score", user) 

385 table.add_row("Critic Score", critic) 

386 table.add_row("Normalized (0-1)", f"{normalized_0_to_1:.3f}" if normalized_0_to_1 else "N/A") 

387 table.add_row("Source", result.source) 

388 table.add_row("URL", result.url or "—") 

389 

390 console.print(table)