"""Wardrobe service and matching.""" from __future__ import annotations from typing import Any from uuid import uuid4 from backend.dto.common import ApiError, ErrorCode from backend.dto.wardrobe_dto import WardrobeItem from core.audit_service import AuditService from core.identity import RequestContext from database.repositories.material_repository import MaterialRepository from database.repositories.profile_repository import ProfileRepository from database.repositories.wardrobe_repository import WardrobeRepository DEFAULT_WARDROBE_CATEGORIES = ("top", "bottom", "dress", "shoes", "accessory") class WardrobeService: def __init__( self, wardrobe_repository: WardrobeRepository, profile_repository: ProfileRepository, material_repository: MaterialRepository, audit_service: AuditService, ): self.wardrobe_repository = wardrobe_repository self.profile_repository = profile_repository self.material_repository = material_repository self.audit_service = audit_service def import_material(self, profile_id: str, payload: dict[str, Any], ctx: RequestContext) -> WardrobeItem: self._ensure_profile(profile_id) material_id = str(payload.get("material_id") or "").strip() wardrobe_category = str(payload.get("wardrobe_category") or "").strip() if not material_id: raise ApiError(ErrorCode.VALIDATION_FAILED, "material_id is required", {"field": "material_id"}) if not wardrobe_category: raise ApiError( ErrorCode.VALIDATION_FAILED, "wardrobe_category is required", {"field": "wardrobe_category"}, ) material = self.material_repository.get_material(material_id) if material is None or material.recognition_status != "confirmed": raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "confirmed material not found", {"material_id": material_id}) item = self.wardrobe_repository.create( { "wardrobe_item_id": payload.get("wardrobe_item_id") or new_wardrobe_item_id(), "profile_id": profile_id, "material_id": material_id, "wardrobe_category": wardrobe_category, "tags": payload.get("tags") or material.tags, "season": payload.get("season"), "style": payload.get("style"), "is_favorite": payload.get("is_favorite", False), } ) self.audit_service.record( ctx=ctx, action="add_wardrobe_item", target_type="wardrobe_item", target_id=item.wardrobe_item_id, after_snapshot=item.to_dict(), ) return item def list_items(self, profile_id: str, wardrobe_category: str | None = None) -> list[WardrobeItem]: self._ensure_profile(profile_id) return self.wardrobe_repository.list_by_profile(profile_id, wardrobe_category) def delete_item(self, profile_id: str, wardrobe_item_id: str, ctx: RequestContext) -> WardrobeItem: self._ensure_profile(profile_id) before = self.wardrobe_repository.get(wardrobe_item_id) if before is None or before.profile_id != profile_id: raise ApiError( ErrorCode.RESOURCE_NOT_FOUND, "wardrobe item not found", {"wardrobe_item_id": wardrobe_item_id}, ) deleted = self.wardrobe_repository.delete(wardrobe_item_id) assert deleted is not None self.audit_service.record( ctx=ctx, action="delete_wardrobe_item", target_type="wardrobe_item", target_id=wardrobe_item_id, before_snapshot=deleted.to_dict(), ) return deleted def match(self, profile_id: str, payload: dict[str, Any], ctx: RequestContext) -> dict[str, Any]: self._ensure_profile(profile_id) categories = _normalize_categories(payload.get("categories")) if not categories: categories = list(DEFAULT_WARDROBE_CATEGORIES) context = _match_context(payload) selected: list[dict[str, Any]] = [] prompt_parts: list[str] = [] missing_categories: list[str] = [] for category in categories: candidates = self.wardrobe_repository.list_by_profile(profile_id, str(category)) if not candidates: missing_categories.append(str(category)) continue scored_candidates = [] for index, item in enumerate(candidates): material = self.material_repository.get_material(item.material_id) if material is None: continue score, breakdown = _score_candidate(item, material, context) scored_candidates.append((score, -index, item, material, breakdown)) if not scored_candidates: missing_categories.append(str(category)) continue score, _order, item, material, breakdown = max(scored_candidates, key=lambda candidate: (candidate[0], candidate[1])) self.wardrobe_repository.mark_used(item.wardrobe_item_id) selected.append( { "wardrobe_item_id": item.wardrobe_item_id, "material_id": material.material_id, "wardrobe_category": item.wardrobe_category, "display_name": material.display_name, "prompt": material.prompt, "tags": item.tags, "season": item.season, "style": item.style, "is_favorite": item.is_favorite, "usage_count": item.usage_count, "score": score, "score_breakdown": breakdown, } ) if material.prompt: prompt_parts.append(material.prompt) fallback_strategy = _fallback_outfit_strategy(payload, categories, missing_categories, selected, context) outfit_prompt = ", ".join(prompt_parts) if not outfit_prompt: outfit_prompt = fallback_strategy["prompt"] result = { "profile_id": profile_id, "selected_materials": selected, "outfit_prompt": outfit_prompt, "fallback_used": not selected, "fallback_supplement_used": bool(selected and missing_categories), "fallback_reason": fallback_strategy["reason"], "fallback_prompt": fallback_strategy["prompt"] if fallback_strategy["reason"] else None, "fallback_strategy": fallback_strategy, "match_details": { "requested_categories": categories, "missing_categories": missing_categories, "matched_count": len(selected), "keywords": sorted(context["keywords"]), "requested_tags": sorted(context["requested_tags"]), "season": context["season"], "style": context["style"], }, } self.audit_service.record( ctx=ctx, action="wardrobe_match", target_type="character_profile", target_id=profile_id, after_snapshot=result, ) return result def _ensure_profile(self, profile_id: str) -> None: profile = self.profile_repository.get(profile_id) if profile is None or profile.status == "deleted": raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "profile not found", {"profile_id": profile_id}) def new_wardrobe_item_id() -> str: return f"wardrobe_{uuid4().hex}" def _normalize_categories(value: Any) -> list[str]: if not isinstance(value, list): return [] categories = [] for item in value: category = str(item or "").strip() if category and category not in categories: categories.append(category) return categories def _match_context(payload: dict[str, Any]) -> dict[str, Any]: keywords = _text_set(payload.get("keywords")) requested_tags = _text_set(payload.get("tags")) | keywords season = _optional_lower(payload.get("season")) style = _optional_lower(payload.get("style")) mood = _optional_lower(payload.get("mood")) weather = _optional_lower(payload.get("weather")) for value in (season, style, mood, weather): if value: requested_tags.add(value) return { "keywords": keywords, "requested_tags": requested_tags, "season": season, "style": style, "mood": mood, "weather": weather, } def _score_candidate(item: WardrobeItem, material, context: dict[str, Any]) -> tuple[int, dict[str, int]]: item_terms = _text_set(item.tags) | _text_set(material.tags) | _words(material.display_name) | _words(material.prompt) requested_tags = context["requested_tags"] tag_overlap = len(item_terms & requested_tags) prompt_hits = sum(1 for keyword in context["keywords"] if keyword and keyword in _search_blob(item, material)) breakdown = { "category": 50, "favorite": 15 if item.is_favorite else 0, "freshness": max(0, 10 - min(item.usage_count, 10)), "tag_overlap": tag_overlap * 8, "prompt_hits": prompt_hits * 3, "season": 12 if context["season"] and _optional_lower(item.season) == context["season"] else 0, "style": 12 if context["style"] and _optional_lower(item.style) == context["style"] else 0, } return sum(breakdown.values()), breakdown def _fallback_outfit_strategy( payload: dict[str, Any], categories: list[str], missing_categories: list[str], selected: list[dict[str, Any]], context: dict[str, Any], ) -> dict[str, Any]: if not missing_categories and selected: return { "name": None, "reason": None, "missing_categories": [], "prompt": "", } reason = "missing_categories" if selected else "no_matching_materials" target_categories = missing_categories or categories descriptors = [_category_fallback(category) for category in target_categories] parts = ["daily outfit fallback"] for key in ("style", "season", "mood", "weather"): if context.get(key): parts.append(str(context[key])) keywords = payload.get("keywords") if isinstance(payload.get("keywords"), list) else [] parts.extend(str(keyword).strip() for keyword in keywords if str(keyword).strip()) if descriptors: parts.append("with " + ", ".join(descriptors)) parts.append("cohesive colors, clean character outfit reference") return { "name": "random_prompt_generation", "reason": reason, "missing_categories": target_categories, "prompt": ", ".join(parts), } def _category_fallback(category: str) -> str: return { "top": "coordinated top", "bottom": "matching bottom", "dress": "one-piece dress alternative", "shoes": "matching shoes", "accessory": "subtle accessory", }.get(str(category), f"matching {category}") def _search_blob(item: WardrobeItem, material) -> str: return " ".join( [ material.display_name or "", material.prompt or "", " ".join(item.tags), " ".join(material.tags), item.season or "", item.style or "", ] ).lower() def _text_set(value: Any) -> set[str]: if isinstance(value, str): values = value.split(",") elif isinstance(value, list): values = value elif isinstance(value, tuple): values = list(value) else: values = [] return {str(item).strip().lower() for item in values if str(item).strip()} def _words(value: Any) -> set[str]: return {part.strip(" ,.;:/\\_-").lower() for part in str(value or "").split() if part.strip(" ,.;:/\\_-")} def _optional_lower(value: Any) -> str | None: text = str(value or "").strip().lower() return text or None