"""Resolve normal and verified advanced materials through one trusted catalog. The two libraries deliberately keep separate persistence models. Generation and workflow code, however, only need the stable :class:`Material` contract. This adapter is the trust boundary between persisted user-editable metadata and the composition priority rules: reserved catalog fields are always replaced by server-derived values and cannot be promoted by writing ordinary metadata. """ from __future__ import annotations from copy import deepcopy from typing import Any from backend.dto.advanced_material_dto import AdvancedMaterial from backend.dto.material_dto import Material, MaterialCategory from database.repositories.advanced_material_repository import AdvancedMaterialRepository from database.repositories.material_repository import MaterialRepository ADVANCED_MATERIAL_ID_PREFIX = "advmat_" ADVANCED_VERIFIED_PRIORITY = 100 _CATALOG_RESERVED_METADATA_KEYS = frozenset( {"library_kind", "priority_class", "material_priority", "verification"} ) class CatalogMaterialMetadata(dict[str, Any]): """Dict-compatible metadata carrying an in-process catalog trust marker. The marker is intentionally an attribute rather than a serializable key. Data loaded from JSON can therefore never manufacture the marker. The object remains JSON-serializable anywhere the existing ``Material`` DTO is serialized. """ __slots__ = ("_advanced_verified",) def __init__(self, value: dict[str, Any], *, advanced_verified: bool): super().__init__(value) self._advanced_verified = bool(advanced_verified) @property def advanced_verified(self) -> bool: return self._advanced_verified def is_trusted_advanced_metadata(value: Any) -> bool: """Return whether metadata was resolved from an active advanced record.""" return ( isinstance(value, CatalogMaterialMetadata) and value.advanced_verified and value.get("library_kind") == "advanced" and value.get("priority_class") == "advanced_verified" and value.get("material_priority") == ADVANCED_VERIFIED_PRIORITY ) class MaterialCatalogResolver: """Expose normal and accepted advanced materials via the legacy DTO.""" def __init__( self, materials: MaterialRepository, advanced_materials: AdvancedMaterialRepository, ): self.materials = materials self.advanced_materials = advanced_materials def get_material(self, material_id: str) -> Material | None: normalized_id = str(material_id or "").strip() if not normalized_id: return None if normalized_id.startswith(ADVANCED_MATERIAL_ID_PREFIX): advanced = self.advanced_materials.get_material(normalized_id) if advanced is None or advanced.status != "active": return None return self._advanced_to_material(advanced) material = self.materials.get_material(normalized_id) return self._normal_material(material) if material is not None else None def get_category(self, category_id: str) -> MaterialCategory | None: return self.materials.get_category(category_id) def update_material(self, material_id: str, payload: dict[str, Any]) -> Material | None: """Update restoration feedback without crossing the library boundary. Catalog identity and priority fields remain server-owned even when the caller supplies a complete metadata replacement. """ normalized_id = str(material_id or "").strip() if normalized_id.startswith(ADVANCED_MATERIAL_ID_PREFIX): current = self.advanced_materials.get_material(normalized_id) if current is None or current.status != "active": return None update = dict(payload or {}) if "metadata" in update: update["metadata"] = _without_catalog_fields(update.get("metadata")) updated = self.advanced_materials.update_material(normalized_id, update) return ( self._advanced_to_material(updated) if updated is not None and updated.status == "active" else None ) update = dict(payload or {}) if "metadata" in update: update["metadata"] = _without_catalog_fields(update.get("metadata")) updated = self.materials.update_material(normalized_id, update) return self._normal_material(updated) if updated is not None else None def _normal_material(self, material: Material) -> Material: metadata = CatalogMaterialMetadata( { **_without_catalog_fields(material.metadata), "library_kind": "standard", "priority_class": "standard", "material_priority": 0, "verification": {}, }, advanced_verified=False, ) return Material( material_id=material.material_id, category_id=material.category_id, display_name=material.display_name, image_uri=material.image_uri, thumbnail_uri=material.thumbnail_uri, prompt=material.prompt, negative_prompt=material.negative_prompt, tags=list(material.tags), recognition_status=material.recognition_status, metadata=metadata, created_at=material.created_at, updated_at=material.updated_at, ) def _advanced_to_material(self, material: AdvancedMaterial) -> Material: attempt = self.advanced_materials.get_attempt(material.accepted_attempt_id) verification: dict[str, Any] = { "status": "accepted", "import_id": material.import_id, "accepted_attempt_id": material.accepted_attempt_id, "source_image_uri": material.source_image_uri, "validation_image_uri": material.validation_image_uri, "validation_thumbnail_uri": material.validation_thumbnail_uri, "accepted_at": material.accepted_at, } if attempt is not None: verification.update( { "attempt_number": attempt.attempt_number, "fidelity_score": attempt.fidelity_score, "decision": attempt.decision, "decision_notes": attempt.decision_notes, "model_route": attempt.model_route, "decided_at": attempt.decided_at, } ) metadata = _without_catalog_fields(material.metadata) capsules = _generation_capsules(material.capsule, metadata) if capsules: metadata["generation_capsules"] = capsules metadata = CatalogMaterialMetadata( { **metadata, "library_kind": "advanced", "priority_class": "advanced_verified", "material_priority": ADVANCED_VERIFIED_PRIORITY, "verification": verification, }, advanced_verified=True, ) return Material( material_id=material.material_id, category_id=material.category_id, display_name=material.display_name, image_uri=material.source_image_uri, thumbnail_uri=material.source_thumbnail_uri, prompt=material.prompt, negative_prompt=material.negative_prompt, tags=list(material.tags), recognition_status="confirmed", metadata=metadata, created_at=material.created_at, updated_at=material.updated_at, ) def _without_catalog_fields(value: Any) -> dict[str, Any]: source = value if isinstance(value, dict) else {} return { str(key): deepcopy(child) for key, child in source.items() if str(key) not in _CATALOG_RESERVED_METADATA_KEYS } def _generation_capsules(capsule: Any, metadata: dict[str, Any]) -> dict[str, Any]: source = capsule if isinstance(capsule, dict) else {} nested = source.get("generation_capsules") if isinstance(nested, dict): return deepcopy(nested) if any(isinstance(source.get(tier), dict) for tier in ("compact", "standard", "detailed")): return deepcopy(source) if source: return {"detailed": deepcopy(source)} existing = metadata.get("generation_capsules") return deepcopy(existing) if isinstance(existing, dict) else {}