from __future__ import annotations import logging from datetime import datetime, timezone from pathlib import Path from fastapi import HTTPException, status from app.core.config import settings from app.repositories.scheme_artifacts import create_scheme_artifact from app.repositories.scheme_versions import update_scheme_version_display_artifact from app.services.storage import save_display_svg from app.services.svg_display_processor import ALLOWED_MODES, generate_display_svg logger = logging.getLogger(__name__) async def regenerate_display_artifact( *, scheme_id: str, scheme_version_id: str, upload_id: str, original_filename: str, sanitized_storage_path: str, mode: str, ) -> dict: if mode not in ALLOWED_MODES: raise HTTPException( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=f"Unsupported display mode: {mode}", ) svg_path = Path(sanitized_storage_path) if not svg_path.exists() or not svg_path.is_file(): raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Sanitized SVG not found for current scheme version", ) sanitized_bytes = svg_path.read_bytes() try: display_bytes, meta = generate_display_svg(sanitized_bytes, mode) except Exception as exc: logger.exception( "display_svg.regenerate failed scheme_id=%s scheme_version_id=%s mode=%s", scheme_id, scheme_version_id, mode, ) raise HTTPException( status_code=status.HTTP_409_CONFLICT, detail=f"Current scheme version is not ready for display rendering: {exc.__class__.__name__}", ) storage_path = save_display_svg( upload_id=upload_id, filename=original_filename, content=display_bytes, ) await create_scheme_artifact( scheme_id=scheme_id, scheme_version_id=scheme_version_id, artifact_type="display_svg", artifact_variant=mode, storage_path=storage_path, status="ready", meta_json=meta, ) if mode == settings.svg_display_mode: await update_scheme_version_display_artifact( scheme_version_id=scheme_version_id, display_svg_storage_path=storage_path, display_svg_status="ready", display_svg_generated_at=datetime.now(timezone.utc), ) return { "scheme_id": scheme_id, "scheme_version_id": scheme_version_id, "artifact_type": "display_svg", "artifact_variant": mode, "storage_path": storage_path, "meta": meta, "generated_at": datetime.now(timezone.utc).isoformat(), }