"""Material library service.""" from __future__ import annotations from typing import Any from uuid import uuid4 from backend.dto.common import ApiError, ErrorCode from backend.dto.material_dto import Material, MaterialCategory, MaterialListResult from core.audit_service import AuditService from core.identity import RequestContext from database.repositories.material_repository import MaterialRepository MATERIAL_STATUSES = {"pending_upload", "pending_recognition", "pending_confirm", "confirmed", "archived"} class MaterialService: def __init__(self, repository: MaterialRepository, audit_service: AuditService): self.repository = repository self.audit_service = audit_service def create_category(self, payload: dict[str, Any], ctx: RequestContext) -> MaterialCategory: name = str(payload.get("name") or "").strip() if not name: raise ApiError(ErrorCode.VALIDATION_FAILED, "category name is required", {"field": "name"}) parent_id = payload.get("parent_id") if parent_id and self.repository.get_category(parent_id) is None: raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "parent category not found", {"parent_id": parent_id}) category = self.repository.create_category( { "category_id": payload.get("category_id") or new_category_id(), "name": name, "parent_id": parent_id, "category_type": payload.get("category_type", "material"), "sort_order": payload.get("sort_order", 0), "metadata": payload.get("metadata") or {}, } ) self.audit_service.record( ctx=ctx, action="create_material_category", target_type="material_category", target_id=category.category_id, after_snapshot=category.to_dict(), ) return category def list_categories(self) -> list[MaterialCategory]: return self.repository.list_categories() def update_category(self, category_id: str, payload: dict[str, Any], ctx: RequestContext) -> MaterialCategory: before = self.get_category(category_id) if "name" in payload and not str(payload["name"]).strip(): raise ApiError(ErrorCode.VALIDATION_FAILED, "category name is required", {"field": "name"}) after = self.repository.update_category(category_id, payload) if after is None: raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "category not found", {"category_id": category_id}) self.audit_service.record( ctx=ctx, action="update_material_category", target_type="material_category", target_id=category_id, before_snapshot=before.to_dict(), after_snapshot=after.to_dict(), ) return after def delete_category(self, category_id: str, ctx: RequestContext) -> MaterialCategory: before = self.repository.delete_category(category_id) if before is None: raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "category not found", {"category_id": category_id}) self.audit_service.record( ctx=ctx, action="delete_material_category", target_type="material_category", target_id=category_id, before_snapshot=before.to_dict(), ) return before def get_category(self, category_id: str) -> MaterialCategory: category = self.repository.get_category(category_id) if category is None: raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "category not found", {"category_id": category_id}) return category def create_material(self, payload: dict[str, Any], ctx: RequestContext) -> Material: display_name = str(payload.get("display_name") or "").strip() if not display_name: raise ApiError(ErrorCode.VALIDATION_FAILED, "display_name is required", {"field": "display_name"}) self._validate_category(payload.get("category_id")) self._validate_storage_uri(payload.get("image_uri"), "image_uri") self._validate_storage_uri(payload.get("thumbnail_uri"), "thumbnail_uri") status = payload.get("recognition_status", "pending_upload") self._validate_status(status) material = self.repository.create_material( { "material_id": payload.get("material_id") or new_material_id(), "category_id": payload.get("category_id"), "display_name": display_name, "image_uri": payload.get("image_uri"), "thumbnail_uri": payload.get("thumbnail_uri"), "prompt": payload.get("prompt"), "negative_prompt": payload.get("negative_prompt"), "tags": payload.get("tags") or [], "recognition_status": status, "metadata": payload.get("metadata") or {}, } ) self.audit_service.record( ctx=ctx, action="create_material", target_type="material", target_id=material.material_id, after_snapshot=material.to_dict(), ) return material def list_materials( self, *, category_id: str | None = None, keyword: str | None = None, page: int = 1, page_size: int = 30, ) -> MaterialListResult: normalized_page = max(page, 1) normalized_page_size = min(max(page_size, 1), 100) items, total = self.repository.list_materials( category_id=category_id, keyword=keyword, page=normalized_page, page_size=normalized_page_size, ) return MaterialListResult(items=items, total=total, page=normalized_page, page_size=normalized_page_size) def get_material(self, material_id: str) -> Material: material = self.repository.get_material(material_id) if material is None or material.recognition_status == "archived": raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "material not found", {"material_id": material_id}) return material def update_material(self, material_id: str, payload: dict[str, Any], ctx: RequestContext) -> Material: before = self.get_material(material_id) if "category_id" in payload: self._validate_category(payload.get("category_id")) if "image_uri" in payload: self._validate_storage_uri(payload.get("image_uri"), "image_uri") if "thumbnail_uri" in payload: self._validate_storage_uri(payload.get("thumbnail_uri"), "thumbnail_uri") if "recognition_status" in payload: self._validate_status(payload["recognition_status"]) update_payload = dict(payload) if "display_name" in update_payload: update_payload["display_name"] = str(update_payload["display_name"]).strip() if not update_payload["display_name"]: raise ApiError(ErrorCode.VALIDATION_FAILED, "display_name is required", {"field": "display_name"}) after = self.repository.update_material(material_id, update_payload) if after is None: raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "material not found", {"material_id": material_id}) self.audit_service.record( ctx=ctx, action="update_material", target_type="material", target_id=material_id, before_snapshot=before.to_dict(), after_snapshot=after.to_dict(), ) return after def delete_material(self, material_id: str, ctx: RequestContext) -> Material: return self.update_material(material_id, {"recognition_status": "archived"}, ctx) def upload_material(self, payload: dict[str, Any], ctx: RequestContext) -> Material: image_uri = payload.get("image_uri") if not image_uri: raise ApiError(ErrorCode.VALIDATION_FAILED, "image_uri is required", {"field": "image_uri"}) display_name = str(payload.get("display_name") or payload.get("filename") or "Uploaded material").strip() return self.create_material( { "category_id": payload.get("category_id"), "display_name": display_name, "image_uri": image_uri, "thumbnail_uri": payload.get("thumbnail_uri") or image_uri, "recognition_status": "pending_recognition", "metadata": { "upload": { "filename": payload.get("filename"), "content_type": payload.get("content_type"), "mock": True, } }, }, ctx, ) def recognize_material(self, material_id: str, ctx: RequestContext) -> Material: material = self.get_material(material_id) if material.recognition_status == "confirmed": return material return self._recognize_material(material, ctx) def re_recognize_material(self, material_id: str, ctx: RequestContext) -> Material: material = self.get_material(material_id) return self._recognize_material(material, ctx) def _recognize_material(self, material: Material, ctx: RequestContext) -> Material: generated_tags = _mock_tags(material) prompt = material.prompt or _mock_prompt(material) after = self.update_material( material.material_id, { "prompt": prompt, "negative_prompt": material.negative_prompt or "body, face, background, watermark", "tags": sorted(set(material.tags + generated_tags)), "recognition_status": "pending_confirm", "metadata": {**material.metadata, "recognition": {"engine": "mock_vlm", "confidence": 0.72}}, }, ctx, ) self.audit_service.record( ctx=ctx, action="recognize_material", target_type="material", target_id=material.material_id, before_snapshot=material.to_dict(), after_snapshot=after.to_dict(), ) return after def confirm_material(self, material_id: str, payload: dict[str, Any], ctx: RequestContext) -> Material: material = self.get_material(material_id) update_payload = { "recognition_status": "confirmed", "display_name": payload.get("display_name", material.display_name), "prompt": payload.get("prompt", material.prompt), "negative_prompt": payload.get("negative_prompt", material.negative_prompt), "tags": payload.get("tags", material.tags), "metadata": {**material.metadata, "confirmed": True}, } after = self.update_material(material_id, update_payload, ctx) self.audit_service.record( ctx=ctx, action="confirm_material", target_type="material", target_id=material_id, before_snapshot=material.to_dict(), after_snapshot=after.to_dict(), ) return after def _validate_category(self, category_id: Any) -> None: if category_id and self.repository.get_category(str(category_id)) is None: raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "category not found", {"category_id": category_id}) def _validate_status(self, status: Any) -> None: if status not in MATERIAL_STATUSES: raise ApiError( ErrorCode.VALIDATION_FAILED, "unsupported material status", {"field": "recognition_status", "allowed": sorted(MATERIAL_STATUSES)}, ) def _validate_storage_uri(self, uri: Any, field: str) -> None: if uri is None: return if not str(uri).startswith("storage://"): raise ApiError(ErrorCode.VALIDATION_FAILED, f"{field} must use storage://", {"field": field}) def new_category_id() -> str: return f"cat_{uuid4().hex}" def new_material_id() -> str: return f"mat_{uuid4().hex}" def _mock_prompt(material: Material) -> str: base = material.display_name.strip().lower().replace("_", " ") return f"{base}, clean product reference, transparent background" def _mock_tags(material: Material) -> list[str]: text = f"{material.display_name} {material.prompt or ''}".lower() tags = ["material"] for keyword in ("white", "blue", "black", "red", "ribbon", "shirt", "blouse", "dress", "skirt", "shoe"): if keyword in text: tags.append(keyword) return tags