"""SpaceForge API routes.""" from __future__ import annotations from pathlib import Path from typing import Any, Optional from fastapi import APIRouter, HTTPException, Query from fastapi.responses import FileResponse, PlainTextResponse from pydantic import BaseModel, Field from backend.app.config import ERSATZ_KEY, MAX_DOWNLOAD_BYTES from backend.app.converters.registry import get_registry from backend.app.providers.huggingface import ( SpaceProviderError, classify_compatibility, fetch_space_info, parse_space_url, redact, ) from backend.app.security.zipsafe import is_within_directory from backend.app.services.builds import build_manager from backend.app.analysis.manifest import build_manifest from backend.app.config import BUILDS_ROOT router = APIRouter(prefix="/api") class AnalyzeRequest(BaseModel): url: Optional[str] = Field(None, description="HF Space URL or owner/name (legacy, used by STUDIUS)") space_url: Optional[str] = Field(None, description="Alias of url") hf_token: Optional[str] = Field( None, description=f"Optional token for private Spaces. Never logged. Example: {ERSATZ_KEY}", ) class BuildRequest(BaseModel): url: Optional[str] = None space_url: Optional[str] = None targets: Optional[list[str]] = None # legacy multi-target (STUDIUS) target: Optional[str] = None # new single-target API mode: Optional[str] = None # local | hybrid | hosted_wrapper (validated against adapter) options: Optional[dict[str, Any]] = None hf_token: Optional[str] = None @router.get("/health") async def health() -> dict[str, object]: from backend.app.converters.mobile.android_sdk import sdk_status return {"status": "ok", "service": "spaceforge", "android_sdk": sdk_status()} @router.get("/targets") async def list_targets() -> dict[str, Any]: reg = get_registry() return { "targets": [ { "id": c.id, "label": c.label, "mode": c.mode, "available": c.available, "stub": c.stub, } for c in reg.values() ] } @router.post("/analyze") async def analyze(body: AnalyzeRequest) -> dict[str, Any]: token = body.hf_token.strip() if body.hf_token else None src = body.space_url or body.url if not src: raise HTTPException(status_code=422, detail={"code": "missing_url", "message": "space_url is required"}) try: owner, name = parse_space_url(src) info = await fetch_space_info(owner, name, token=token) compat = classify_compatibility(info) try: manifest = await build_manifest(info, token) except Exception as me: # analysis extras must never break legacy analyze manifest = {"error": type(me).__name__} except SpaceProviderError as e: raise HTTPException(status_code=e.status, detail={"code": e.code, "message": redact(e.message, token)}) from e except Exception as e: raise HTTPException(status_code=500, detail={"code": "internal", "message": type(e).__name__}) from e return {"space": info, "compatibility": compat, "manifest": manifest} @router.post("/build") async def build(body: BuildRequest) -> dict[str, Any]: token = body.hf_token.strip() if body.hf_token else None reg = get_registry() src = body.space_url or body.url targets = list(body.targets or []) + ([body.target] if body.target else []) if not src or not targets: raise HTTPException(status_code=422, detail={"code": "missing_field", "message": "space_url and target are required"}) unknown = [t for t in targets if t not in reg] if unknown: raise HTTPException(status_code=400, detail={"code": "unknown_target", "message": f"Unknown: {unknown}"}) try: owner, name = parse_space_url(src) info = await fetch_space_info(owner, name, token=token) except SpaceProviderError as e: raise HTTPException(status_code=e.status, detail={"code": e.code, "message": redact(e.message, token)}) from e stubs = [t for t in targets if not reg[t].available] if stubs and body.target: raise HTTPException(status_code=400, detail={"code": "target_unavailable", "message": f"Target not buildable here yet: {stubs}"}) if body.mode: bad = [t for t in targets if reg[t].mode != body.mode] if bad: raise HTTPException(status_code=400, detail={"code": "mode_mismatch", "message": f"{bad} cannot be built in mode '{body.mode}' (adapter mode: {[reg[t].mode for t in bad]})"}) opts = dict(body.options or {}) if body.mode: opts["mode"] = body.mode job = await build_manager.create(info, targets, opts) return {"build_id": job.id, "status": job.status} @router.get("/build/{build_id}") async def build_status(build_id: str) -> dict[str, Any]: job = build_manager.get(build_id) if not job: raise HTTPException(status_code=404, detail={"code": "not_found", "message": "Build not found or expired"}) return job.to_public() @router.get("/build/{build_id}/logs") async def build_logs(build_id: str) -> PlainTextResponse: job = build_manager.get(build_id) if not job: raise HTTPException(status_code=404, detail={"code": "not_found", "message": "Build not found or expired"}) # Ensure secrets never appear (token not stored in logs by design) return PlainTextResponse("\n".join(job.logs) + "\n", media_type="text/plain") @router.get("/build/{build_id}/download") async def build_download(build_id: str, target: Optional[str] = Query(None)) -> FileResponse: job = build_manager.get(build_id) if not job: raise HTTPException(status_code=404, detail={"code": "not_found", "message": "Build not found or expired"}) if target is None: if len(job.targets) != 1: raise HTTPException(status_code=400, detail={"code": "target_required", "message": "Multi-target build: pass ?target="}) target = job.targets[0] meta = job.artifacts.get(target) if not meta: err = job.errors.get(target) raise HTTPException( status_code=404, detail={"code": "no_artifact", "message": err or f"No artifact for target {target}"}, ) path = (job.work_dir / meta["path_name"]) if job.work_dir else None if not path or not path.exists(): raise HTTPException(status_code=404, detail={"code": "missing_file", "message": "Artifact file missing"}) if not is_within_directory(BUILDS_ROOT, path): raise HTTPException(status_code=400, detail={"code": "path_traversal", "message": "Blocked"}) size = path.stat().st_size if size > MAX_DOWNLOAD_BYTES: raise HTTPException( status_code=413, detail={"code": "too_large", "message": f"Artifact exceeds limit ({MAX_DOWNLOAD_BYTES} bytes)"}, ) return FileResponse( path, filename=meta["filename"], media_type=meta.get("media_type") or "application/zip", ) @router.delete("/build/{build_id}") async def build_delete(build_id: str) -> dict[str, Any]: ok = await build_manager.delete(build_id) if not ok: raise HTTPException(status_code=404, detail={"code": "not_found", "message": "Build not found"}) return {"deleted": True, "id": build_id}