refactor: Batch 3 — routes/import_routes.py and routes/precon.py
This commit is contained in:
1 parent
b0666bb3fd
commit
553e07980f
2 files changed
+224
No files matched your search
@@ -0,0 +1,133 @@
|
||||
"""
|
||||
routes/import_routes.py
|
||||
=======================
|
||||
Deck import + commander meta endpoints:
|
||||
POST /api/lab/import/url
|
||||
POST /api/lab/import/text
|
||||
GET /api/lab/meta/commanders
|
||||
GET /api/lab/meta/search
|
||||
POST /api/lab/meta/fetch
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional
|
||||
|
||||
from routes.shared import get as _get
|
||||
|
||||
router = APIRouter(prefix="/api/lab", tags=["import"])
|
||||
|
||||
|
||||
class ImportUrlRequest(BaseModel):
|
||||
url: str
|
||||
|
||||
|
||||
class ImportTextRequest(BaseModel):
|
||||
text: str
|
||||
commander: Optional[str] = None
|
||||
|
||||
|
||||
class MetaFetchRequest(BaseModel):
|
||||
commander: str
|
||||
|
||||
|
||||
@router.post("/import/url")
|
||||
async def import_from_url(req: ImportUrlRequest):
|
||||
"""Import a deck from Archidekt or EDHREC URL."""
|
||||
_import_from_url = _get("_import_from_url")
|
||||
_save_profile_to_dck = _get("_save_profile_to_dck")
|
||||
url = req.url.strip()
|
||||
try:
|
||||
profile = _import_from_url(url)
|
||||
dck_path = _save_profile_to_dck(profile)
|
||||
return {
|
||||
"success": True,
|
||||
"deckName": profile["name"],
|
||||
"commander": profile["commander"],
|
||||
"source": profile["source"],
|
||||
"sourceUrl": profile["sourceUrl"],
|
||||
"totalCards": profile["totalCards"],
|
||||
"dckFile": dck_path.stem,
|
||||
"colorIdentity": profile.get("colorIdentity", []),
|
||||
"archetype": profile.get("archetype"),
|
||||
}
|
||||
except Exception as e:
|
||||
raise HTTPException(400, str(e))
|
||||
|
||||
|
||||
@router.post("/import/text")
|
||||
async def import_from_text(req: ImportTextRequest):
|
||||
"""Import a deck from plain text card list."""
|
||||
_parse_text_decklist = _get("_parse_text_decklist")
|
||||
_save_profile_to_dck = _get("_save_profile_to_dck")
|
||||
try:
|
||||
profile = _parse_text_decklist(req.text, req.commander)
|
||||
dck_path = _save_profile_to_dck(profile)
|
||||
return {
|
||||
"success": True,
|
||||
"deckName": profile["name"],
|
||||
"commander": profile["commander"],
|
||||
"source": "Text Import",
|
||||
"totalCards": profile["totalCards"],
|
||||
"dckFile": dck_path.stem,
|
||||
}
|
||||
except Exception as e:
|
||||
raise HTTPException(400, str(e))
|
||||
|
||||
|
||||
@router.get("/meta/commanders")
|
||||
async def list_meta_commanders():
|
||||
"""List available commanders in the meta mapping."""
|
||||
COMMANDER_META = _get("COMMANDER_META")
|
||||
commanders = []
|
||||
for name, entries in COMMANDER_META.items():
|
||||
entry = entries[0] if entries else {}
|
||||
commanders.append({
|
||||
"name": name,
|
||||
"archetype": entry.get("archetype", ""),
|
||||
"colorIdentity": entry.get("colorIdentity", []),
|
||||
"source": entry.get("source", "edhrec"),
|
||||
})
|
||||
return {"commanders": commanders}
|
||||
|
||||
|
||||
@router.get("/meta/search")
|
||||
async def search_meta_commanders(q: str = ""):
|
||||
"""Search commanders by partial name match."""
|
||||
COMMANDER_META = _get("COMMANDER_META")
|
||||
query = q.lower()
|
||||
matches = []
|
||||
for name, entries in COMMANDER_META.items():
|
||||
if query in name.lower():
|
||||
entry = entries[0] if entries else {}
|
||||
matches.append({
|
||||
"name": name,
|
||||
"archetype": entry.get("archetype", ""),
|
||||
"colorIdentity": entry.get("colorIdentity", []),
|
||||
})
|
||||
return {"results": matches}
|
||||
|
||||
|
||||
@router.post("/meta/fetch")
|
||||
async def fetch_meta_deck(req: MetaFetchRequest):
|
||||
"""Fetch EDHREC average deck for a commander."""
|
||||
_fetch_edhrec_average = _get("_fetch_edhrec_average")
|
||||
_save_profile_to_dck = _get("_save_profile_to_dck")
|
||||
try:
|
||||
profile = _fetch_edhrec_average(req.commander)
|
||||
dck_path = _save_profile_to_dck(profile)
|
||||
return {
|
||||
"success": True,
|
||||
"deckName": profile["name"],
|
||||
"commander": profile["commander"],
|
||||
"source": "EDHREC Average",
|
||||
"sourceUrl": profile.get("sourceUrl", ""),
|
||||
"totalCards": profile["totalCards"],
|
||||
"dckFile": dck_path.stem,
|
||||
"colorIdentity": profile.get("colorIdentity", []),
|
||||
"sampleSize": profile.get("sampleSize"),
|
||||
}
|
||||
except Exception as e:
|
||||
raise HTTPException(400, f"Failed to fetch meta deck for '{req.commander}': {str(e)}")
|
||||
@@ -0,0 +1,91 @@
|
||||
"""
|
||||
routes/precon.py
|
||||
================
|
||||
Precon deck management endpoints:
|
||||
GET /api/lab/precons
|
||||
POST /api/lab/precons/install
|
||||
POST /api/lab/precons/install-batch
|
||||
POST /api/lab/precons/refresh
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
|
||||
from routes.shared import get as _get
|
||||
|
||||
router = APIRouter(prefix="/api/lab", tags=["precon"])
|
||||
|
||||
|
||||
@router.get("/precons")
|
||||
async def list_precons():
|
||||
"""List all available precon decks."""
|
||||
PRECON_INDEX = _get("PRECON_INDEX")
|
||||
return {"precons": PRECON_INDEX}
|
||||
|
||||
|
||||
@router.post("/precons/install")
|
||||
async def install_precon(req: dict):
|
||||
"""Install a precon deck to the Forge decks directory."""
|
||||
PRECON_DIR = _get("PRECON_DIR")
|
||||
CFG = _get("CFG")
|
||||
import os
|
||||
file_name = req.get("fileName", "")
|
||||
if not file_name:
|
||||
raise HTTPException(400, "fileName is required")
|
||||
src = PRECON_DIR / file_name
|
||||
if not src.exists():
|
||||
raise HTTPException(404, f"Precon not found: {file_name}")
|
||||
decks_dir = CFG.forge_decks_dir
|
||||
if not decks_dir or not os.path.isdir(decks_dir):
|
||||
raise HTTPException(500, f"Forge decks directory not found: {decks_dir}")
|
||||
dst = Path(decks_dir) / file_name
|
||||
shutil.copy2(str(src), str(dst))
|
||||
deck_name = file_name.replace(".dck", "")
|
||||
return {
|
||||
"installed": True,
|
||||
"deckName": deck_name,
|
||||
"destination": str(dst),
|
||||
"message": f"Installed {deck_name} to Forge decks",
|
||||
}
|
||||
|
||||
|
||||
@router.post("/precons/install-batch")
|
||||
async def install_precons_batch(req: dict):
|
||||
"""Install multiple precon decks at once."""
|
||||
PRECON_DIR = _get("PRECON_DIR")
|
||||
CFG = _get("CFG")
|
||||
import os
|
||||
file_names = req.get("fileNames", [])
|
||||
if not file_names:
|
||||
raise HTTPException(400, "fileNames list is required")
|
||||
decks_dir = CFG.forge_decks_dir
|
||||
if not decks_dir or not os.path.isdir(decks_dir):
|
||||
raise HTTPException(500, f"Forge decks directory not found: {decks_dir}")
|
||||
results = []
|
||||
for file_name in file_names:
|
||||
src = PRECON_DIR / file_name
|
||||
if not src.exists():
|
||||
results.append({"fileName": file_name, "installed": False, "error": "not found"})
|
||||
continue
|
||||
dst = Path(decks_dir) / file_name
|
||||
shutil.copy2(str(src), str(dst))
|
||||
deck_name = file_name.replace(".dck", "")
|
||||
results.append({"fileName": file_name, "installed": True, "deckName": deck_name})
|
||||
return {"results": results}
|
||||
|
||||
|
||||
@router.post("/precons/refresh")
|
||||
async def refresh_precons():
|
||||
"""Force re-download of all Commander precon decks from GitHub."""
|
||||
download_precon_database = _get("download_precon_database")
|
||||
result = download_precon_database(force=True)
|
||||
if result.get("error"):
|
||||
raise HTTPException(502, result["error"])
|
||||
return {
|
||||
"message": f"Downloaded {result['downloaded']} Commander precon decks",
|
||||
"total": result.get("total", 0),
|
||||
}
|
||||
Reference in new issue
Block a user