from __future__ import annotations from datetime import date, datetime from enum import StrEnum from typing import Any from uuid import UUID from pydantic import BaseModel, ConfigDict, Field, computed_field, model_validator from app.db.enums import ModuleStatus, RecordStatus class ContentKind(StrEnum): POINT = "point" PATTERN = "pattern" NUTRITION = "nutrition" THERAPEUTIC = "therapeutic" class CreateContentRequest(BaseModel): content_kind: ContentKind title: str slug: str summary: str | None = None class ModuleRequest(BaseModel): """Exactly one of module_id or module_code must be supplied.""" module_id: UUID | None = None module_code: str | None = None @model_validator(mode="after") def validate_request(self) -> "ModuleRequest": has_id = self.module_id is not None has_code = self.module_code is not None if has_id == has_code: raise ValueError("Provide exactly one of module_id or module_code.") if self.module_code is not None: normalized = self.module_code.strip() if not normalized: raise ValueError("module_code must not be blank.") self.module_code = normalized return self class ModuleSummaryResponse(BaseModel): model_config = ConfigDict(from_attributes=True, populate_by_name=True) id: UUID code: str name: str slug: str default_template_code: str | None = None class ModuleResponse(BaseModel): """Complete module projection safe for ORM -> Pydantic serialization.""" model_config = ConfigDict(from_attributes=True, populate_by_name=True) id: UUID code: str name: str slug: str description: str | None = None default_template_code: str | None = None thumbnail_media_asset_id: UUID | None = None status: ModuleStatus is_active: bool preview_enabled: bool preview_item_limit: int release_version: str | None = None expected_release_date: date | None = None release_notes: str | None = None # ORM attribute is metadata_json; API field remains metadata. metadata: dict[str, Any] = Field( default_factory=dict, validation_alias="metadata_json", serialization_alias="metadata", ) @computed_field @property def category(self) -> str: from app.features.admin.services.module_service import resolve_module_category return resolve_module_category(self.metadata) created_by: UUID | None = None updated_by: UUID | None = None created_at: datetime updated_at: datetime class ModuleListResponse(BaseModel): modules: list[ModuleResponse] = Field(default_factory=list) class ContentItemResponse(BaseModel): model_config = ConfigDict(from_attributes=True, populate_by_name=True) id: UUID content_kind: ContentKind | None = None title: str slug: str summary: str | None = None status: RecordStatus is_active: bool version_no: int metadata: dict[str, Any] = Field( default_factory=dict, validation_alias="metadata_json", serialization_alias="metadata", ) published_at: datetime | None = None created_at: datetime updated_at: datetime class ContentListItemResponse(BaseModel): id: UUID content_kind: ContentKind | None = None title: str slug: str summary: str | None = None thumbnail_media_id: UUID | None = None has_detail: bool = True class ModuleContentItemResponse(BaseModel): module_id: UUID content_id: UUID sort_order: int is_highlighted: bool created_at: datetime created_by: UUID | None = None content: ContentListItemResponse class ModuleContentListResponse(BaseModel): module: ModuleSummaryResponse items: list[ModuleContentItemResponse] = Field(default_factory=list) class ContentReferenceTargetResponse(BaseModel): """Hydrated destination identity for a content_ref payload.""" module_code: str template_code: str source_key: str content_id: UUID class ContentReferenceResponse(BaseModel): """Canonical hydrated content reference shape used inside dynamic data.""" type: str = "content_ref" label: str | None = None target: ContentReferenceTargetResponse class ContentMediaResponse(BaseModel): """Normalized relational media projection for mobile/web clients.""" id: UUID media_asset_id: UUID media_role: str usage_type: str sort_order: int caption: str | None = None alt_text: str | None = None mime_type: str | None = None width: int | None = None height: int | None = None storage_key: str | None = None url: str | None = None requires_auth: bool = False class ContentDetailResponse(BaseModel): """data must contain JSON-safe values only, never ORM entities.""" module: ModuleSummaryResponse content: ContentItemResponse data: dict[str, Any] = Field(default_factory=dict) media: list[ContentMediaResponse] = Field(default_factory=list) class PublishContentResponse(BaseModel): model_config = ConfigDict(from_attributes=True) id: UUID status: RecordStatus published_at: datetime | None = None updated_by: UUID | None = None class ModuleTemplateContentRequest(BaseModel): """ Retrieve all content belonging to one module and one template. Exactly one module identifier is required: - module_id - module_code template_code is always required. """ module_id: UUID | None = None module_code: str | None = None template_code: str @model_validator(mode="after") def validate_request( self, ) -> "ModuleTemplateContentRequest": has_module_id = ( self.module_id is not None ) has_module_code = ( self.module_code is not None ) if ( has_module_id == has_module_code ): raise ValueError( "Provide exactly one of " "module_id or module_code." ) template_code = ( self.template_code.strip() ) if not template_code: raise ValueError( "template_code is required." ) self.template_code = ( template_code ) if self.module_code is not None: module_code = ( self.module_code.strip() ) if not module_code: raise ValueError( "module_code must not be blank." ) self.module_code = module_code return self class TemplateSummaryResponse(BaseModel): id: UUID code: str name: str attribute_prefix_code: str attribute_prefix_name: str class ModuleTemplateContentResponse(BaseModel): """ All content for: module + template/definition-set """ module: ModuleSummaryResponse template: TemplateSummaryResponse items: list[ ContentListItemResponse ] = Field( default_factory=list ) class AttributeDefinitionResponse(BaseModel): id: UUID code: str attribute_key: str label: str definition_kind: str data_type: str | None = None is_root: bool is_required: bool is_searchable: bool is_filterable: bool is_multivalue: bool sort_order: int allowed_values: list[Any] | None = None metadata: dict[str, Any] = Field(default_factory=dict) children: list["AttributeDefinitionResponse"] = Field( default_factory=list ) class TemplateAttributeDefinitionsResponse(BaseModel): template: TemplateSummaryResponse attributes: list[AttributeDefinitionResponse] = Field( default_factory=list ) class ModuleTemplateContentDetailItem(BaseModel): module_content_sort_order: int is_highlighted: bool content: ContentItemResponse data: dict[str, Any] = Field(default_factory=dict) media: list[ContentMediaResponse] = Field(default_factory=list) class ModuleTemplateContentDetailResponse(BaseModel): module: ModuleSummaryResponse template: TemplateSummaryResponse items: list[ModuleTemplateContentDetailItem] = Field( default_factory=list ) # ============================================================================= # TEMPLATE PRESENTATION + SEARCH CONTRACTS # ============================================================================= class StrictModel(BaseModel): model_config = ConfigDict(extra="forbid") class PresentationMode(StrEnum): COLLECTION = "collection" SINGLE = "single" class EmptyBehavior(StrEnum): HIDE = "hide" SHOW = "show" class AttributeVisibility(StrEnum): SHOW = "show" HIDE = "hide" class LogicalOperator(StrEnum): AND = "and" OR = "or" class SearchOperator(StrEnum): EQ = "eq" NEQ = "neq" CONTAINS = "contains" STARTS_WITH = "starts_with" IN = "in" GT = "gt" GTE = "gte" LT = "lt" LTE = "lte" class SortDirection(StrEnum): ASC = "asc" DESC = "desc" class TemplateRendererContract(StrictModel): collection: str | None = None collection_item: str | None = None detail: str @model_validator(mode="after") def validate_codes(self) -> "TemplateRendererContract": self.detail = self.detail.strip() if not self.detail: raise ValueError("detail renderer code is required") if self.collection is not None: self.collection = self.collection.strip() if not self.collection: raise ValueError("collection renderer code cannot be blank") if self.collection_item is not None: self.collection_item = self.collection_item.strip() if not self.collection_item: raise ValueError("collection_item renderer code cannot be blank") return self class TemplateAttributePresentationContract(StrictModel): attribute_key: str = Field(min_length=1, max_length=512) visibility: AttributeVisibility = AttributeVisibility.SHOW empty_behavior: EmptyBehavior = EmptyBehavior.HIDE empty_text: str | None = Field(default=None, max_length=1000) display_order: int | None = Field(default=None, ge=0) @model_validator(mode="after") def validate_empty_text(self) -> "TemplateAttributePresentationContract": self.attribute_key = self.attribute_key.strip() if not self.attribute_key: raise ValueError("attribute_key cannot be blank") if self.empty_text is not None: self.empty_text = self.empty_text.strip() if not self.empty_text: self.empty_text = None if self.empty_behavior == EmptyBehavior.HIDE and self.empty_text is not None: raise ValueError( "empty_text is only valid when empty_behavior='show'" ) return self class TemplatePresentationContract(StrictModel): mode: PresentationMode renderers: TemplateRendererContract attributes: list[TemplateAttributePresentationContract] = Field( default_factory=list ) @model_validator(mode="after") def validate_mode_contract(self) -> "TemplatePresentationContract": if self.mode == PresentationMode.COLLECTION: if not self.renderers.collection: raise ValueError("collection mode requires renderers.collection") if not self.renderers.collection_item: raise ValueError("collection mode requires renderers.collection_item") else: if self.renderers.collection is not None: raise ValueError("single mode must not define renderers.collection") if self.renderers.collection_item is not None: raise ValueError("single mode must not define renderers.collection_item") return self class SearchFieldContract(StrictModel): attribute_key: str label: str operators: list[SearchOperator] renderer_hint: str | None = None allowed_values: list[Any] | None = None @model_validator(mode="after") def validate_field(self) -> "SearchFieldContract": self.attribute_key = self.attribute_key.strip() self.label = self.label.strip() if not self.attribute_key: raise ValueError("attribute_key is required") if not self.label: raise ValueError("label is required") if not self.operators: raise ValueError("at least one search operator is required") if self.renderer_hint is not None: self.renderer_hint = self.renderer_hint.strip() or None return self class SortFieldContract(StrictModel): field: str label: str @model_validator(mode="after") def validate_field(self) -> "SortFieldContract": self.field = self.field.strip() self.label = self.label.strip() if not self.field: raise ValueError("sort field is required") if not self.label: raise ValueError("sort label is required") return self class SortCriterion(StrictModel): field: str direction: SortDirection @model_validator(mode="after") def validate_field(self) -> "SortCriterion": self.field = self.field.strip() if not self.field: raise ValueError("sort field is required") return self class SearchProfileContract(StrictModel): free_text_enabled: bool = True default_logic: LogicalOperator = LogicalOperator.AND fields: list[SearchFieldContract] = Field(default_factory=list) sort_fields: list[SortFieldContract] = Field(default_factory=list) default_sort: list[SortCriterion] = Field(default_factory=list) @model_validator(mode="after") def validate_default_sort(self) -> "SearchProfileContract": allowed = {item.field for item in self.sort_fields} invalid = [item.field for item in self.default_sort if item.field not in allowed] if invalid: raise ValueError( "default_sort contains fields not present in sort_fields: " + ", ".join(sorted(set(invalid))) ) return self class TemplateContractResponse(StrictModel): template_code: str module_code: str | None = None presentation: TemplatePresentationContract search: SearchProfileContract class SearchCriterion(StrictModel): attribute_key: str = Field(min_length=1, max_length=512) operator: SearchOperator value: Any @model_validator(mode="after") def normalize_attribute_key(self) -> "SearchCriterion": self.attribute_key = self.attribute_key.strip() if not self.attribute_key: raise ValueError("attribute_key is required") return self class ContentSearchRequest(StrictModel): module_id: UUID | None = None module_code: str | None = Field(default=None, min_length=1, max_length=128) template_code: str = Field(min_length=1, max_length=128) query: str | None = Field(default=None, max_length=500) # Optional attribute-scoped free-text search. When empty, repository # search remains backward-compatible and searches title/summary plus all # active searchable scalar text/rich-text attributes. search_attributes: list[str] = Field(default_factory=list, max_length=50) logic: LogicalOperator = LogicalOperator.AND filters: list[SearchCriterion] = Field(default_factory=list, max_length=50) sort: list[SortCriterion] = Field(default_factory=list, max_length=5) page: int = Field(default=1, ge=1) page_size: int = Field(default=25, ge=1, le=100) @model_validator(mode="after") def validate_identity(self) -> "ContentSearchRequest": has_id = self.module_id is not None has_code = self.module_code is not None if has_id == has_code: raise ValueError("Provide exactly one of module_id or module_code") self.template_code = self.template_code.strip() if not self.template_code: raise ValueError("template_code is required") if self.module_code is not None: self.module_code = self.module_code.strip() if not self.module_code: raise ValueError("module_code must not be blank") if self.query is not None: self.query = self.query.strip() or None return self class SearchContentItem(StrictModel): id: UUID content_kind: str | None = None title: str slug: str summary: str | None = None attributes: dict[str, Any] = Field(default_factory=dict) class ContentSearchResponse(StrictModel): page: int page_size: int total: int items: list[SearchContentItem] class ModuleSearchFieldContract(StrictModel): attribute_key: str = Field(min_length=1, max_length=512) label: str = Field(min_length=1, max_length=512) template_code: str = Field(min_length=1, max_length=128) template_name: str = Field(min_length=1, max_length=512) data_type: str | None = None is_searchable: bool = False is_filterable: bool = False operators: list[SearchOperator] = Field(default_factory=list) default_operator: SearchOperator | None = None renderer_hint: str | None = None allowed_values: list[Any] | None = None @model_validator(mode="after") def validate_module_search_field(self) -> "ModuleSearchFieldContract": self.attribute_key = self.attribute_key.strip() self.label = self.label.strip() self.template_code = self.template_code.strip() self.template_name = self.template_name.strip() if self.is_filterable and not self.operators: raise ValueError("filterable module search fields require operators") if self.default_operator is not None and self.default_operator not in self.operators: raise ValueError("default_operator must be present in operators") return self class ModuleSearchContractResponse(StrictModel): module_code: str = Field(min_length=1, max_length=128) fields: list[ModuleSearchFieldContract] = Field(default_factory=list) sort_fields: list[SortFieldContract] = Field(default_factory=list) default_sort: list[SortCriterion] = Field(default_factory=list) class ModuleContentSearchRequest(StrictModel): module_id: UUID | None = None module_code: str | None = Field(default=None, min_length=1, max_length=128) query: str | None = Field(default=None, max_length=500) search_attributes: list[str] = Field(default_factory=list, max_length=100) logic: LogicalOperator = LogicalOperator.AND filters: list[SearchCriterion] = Field(default_factory=list, max_length=100) sort: list[SortCriterion] = Field(default_factory=list, max_length=3) page: int = Field(default=1, ge=1) page_size: int = Field(default=25, ge=1, le=100) @model_validator(mode="after") def validate_module_identity(self) -> "ModuleContentSearchRequest": has_id = self.module_id is not None has_code = self.module_code is not None if has_id == has_code: raise ValueError("Provide exactly one of module_id or module_code") if self.module_code is not None: self.module_code = self.module_code.strip() if not self.module_code: raise ValueError("module_code must not be blank") if self.query is not None: self.query = self.query.strip() or None self.search_attributes = list(dict.fromkeys( key.strip() for key in self.search_attributes if key.strip() )) return self class ModuleSearchContentItem(StrictModel): id: UUID template_code: str template_name: str content_kind: str | None = None title: str slug: str summary: str | None = None class ModuleContentSearchResponse(StrictModel): page: int page_size: int total: int items: list[ModuleSearchContentItem] = Field(default_factory=list)