from __future__ import annotations import json from typing import Any, Mapping from uuid import UUID, uuid4 from sqlalchemy import text from sqlalchemy.ext.asyncio import AsyncSession from .schema import CONTENT_SCHEMA, resolve_content_schema from .models import ( AttributeDefinition, BatchSeedSummary, ContentSeedResult, DefinitionGraph, DefinitionSet, ) from .validators import ( ContentValidationError, DefinitionNotFoundError, build_source_key, convert_scalar_value, slugify, validate_content_document, validate_object_input, ) class ContentSeeder: RESERVED_ROOT_FIELDS = {"code", "slug", "title", "summary", "metadata"} def __init__( self, session: AsyncSession, *, schema: str = CONTENT_SCHEMA, max_depth: int = 32, ) -> None: self._session = session self._schema = resolve_content_schema(schema) self._max_depth = max_depth async def seed_document( self, *, definition_set_code: str, document: Mapping[str, Any], publish: bool = False, continue_on_error: bool = False, content_codes: set[str] | None = None, ) -> BatchSeedSummary: rows = validate_content_document(document) if content_codes: requested_by_key = { code.strip().casefold(): code.strip() for code in content_codes if code.strip() } if not requested_by_key: raise ContentValidationError( "content_codes must contain at least one non-empty code" ) selected_rows: list[Mapping[str, Any]] = [] found_keys: set[str] = set() for row in rows: raw_code = row.get("code") if not isinstance(raw_code, str) or not raw_code.strip(): # Preserve the existing row-level validation behavior for # full runs. During a targeted run, rows without a usable # authoring identity cannot match a requested content code. continue key = raw_code.strip().casefold() if key in requested_by_key: selected_rows.append(row) found_keys.add(key) missing = [ requested_by_key[key] for key in requested_by_key.keys() - found_keys ] if missing: raise ContentValidationError( "Requested content code(s) not found in source document: " + ", ".join(sorted(missing)) ) rows = selected_rows definition_set = await self._load_definition_set(definition_set_code) graph = await self._load_definition_graph(definition_set) results: list[ContentSeedResult] = [] errors: list[str] = [] for row_number, content in enumerate(rows, start=1): try: # Normalize generic content references before validation and # persistence. This uses the same slugify() convention as the # canonical content_items.source_key generated in _seed_row(). normalized_content = self._normalize_content_references(content) async with self._session.begin_nested(): result = await self._seed_row( row_number=row_number, graph=graph, content=normalized_content, publish=publish, ) results.append(result) except Exception as exc: message = f"row {row_number}: {exc}" errors.append(message) if not continue_on_error: raise ContentValidationError(message) from exc return BatchSeedSummary( total_rows=len(rows), succeeded=len(results), failed=len(errors), results=tuple(results), errors=tuple(errors), ) @classmethod def _normalize_content_references(cls, value: Any) -> Any: """ Recursively convert author-facing ``content_ref`` objects into the canonical persisted reference representation. Source/authoring contract:: { "type": "content_ref", "label": "ST-36", "target": { "module_code": "M0001", "template_code": "M0001_CT0003", "source_code": "ST-36" } } Persisted contract:: { "type": "content_ref", "label": "ST-36", "target": { "module_code": "M0001", "template_code": "M0001_CT0003", "source_key": "M0001_CT0003:st-36" } } The traversal is deliberately generic and recursive. A content_ref can therefore appear at the root, inside an object, in an array, or at any future nesting depth without changing the reference contract. ``source_code`` is an author-facing stable identity and is never persisted. ``source_key`` is derived here using the same slugify() convention used for ``content_items.source_key``. This prevents source JSON authors from having to know the database canonicalization rules. """ if isinstance(value, list): return [cls._normalize_content_references(item) for item in value] if not isinstance(value, Mapping): return value normalized = { key: cls._normalize_content_references(child) for key, child in value.items() } reference_type = value.get("type") if reference_type in {"content_ref", "template_ref"} and "presentation" in value: raise ContentValidationError( f"{reference_type}.presentation is not allowed in content data; " "define link rendering in the template presentation contract instead" ) if reference_type != "content_ref": return normalized target = normalized.get("target") if not isinstance(target, Mapping): raise ContentValidationError( "content_ref.target must be a JSON object" ) target_dict = dict(target) # Source JSON must use the author-facing source_code contract. Keeping # source_key/content_id out of source files eliminates ambiguous or # stale runtime identity from authored data. if "source_key" in target_dict: raise ContentValidationError( "content_ref.target.source_key is not allowed in seed source " "JSON; use content_ref.target.source_code instead" ) if "content_id" in target_dict: raise ContentValidationError( "content_ref.target.content_id is runtime data and must not be " "provided in seed source JSON" ) module_code = cls._required_content_reference_string( target_dict, "module_code" ).upper() template_code = cls._required_content_reference_string( target_dict, "template_code" ).upper() source_code = cls._required_content_reference_string( target_dict, "source_code" ) target_dict["module_code"] = module_code target_dict["template_code"] = template_code try: target_dict["source_key"] = build_source_key( template_code=template_code, source_code=source_code, ) except Exception as exc: raise ContentValidationError( f"Invalid content_ref target identity: {exc}" ) from exc target_dict.pop("source_code", None) normalized["target"] = target_dict return normalized @staticmethod def _required_content_reference_string( target: Mapping[str, Any], key: str, ) -> str: value = target.get(key) if not isinstance(value, str) or not value.strip(): raise ContentValidationError( f"content_ref.target.{key} must be a non-empty string" ) return value.strip() async def _load_definition_set(self, code: str) -> DefinitionSet: result = await self._session.execute( text( f""" select id, code, name, attribute_prefix_code, attribute_prefix_name, content_kind::text as content_kind, description from {self._schema}.attribute_definition_sets where code = :code and is_active = true """ ), {"code": code}, ) row = result.mappings().one_or_none() if row is None: raise DefinitionNotFoundError(f"Definition set {code!r} does not exist") return DefinitionSet( id=row["id"], code=row["code"], name=row["name"], attribute_prefix_code=row["attribute_prefix_code"], attribute_prefix_name=row["attribute_prefix_name"], content_kind=row["content_kind"], description=row["description"], ) async def _load_definition_graph(self, definition_set: DefinitionSet) -> DefinitionGraph: result = await self._session.execute( text( f""" select id, attribute_definition_set_id, attribute_key, attribute_label, data_type, definition_kind, is_root, is_required, is_multivalue, allowed_values, sort_order, metadata from {self._schema}.attribute_definitions where attribute_definition_set_id = :definition_set_id and is_active = true order by sort_order, attribute_key, id """ ), {"definition_set_id": definition_set.id}, ) prefix = definition_set.attribute_prefix_code + "." by_id: dict[UUID, AttributeDefinition] = {} for row in result.mappings(): attribute_key = str(row["attribute_key"]) if not attribute_key.startswith(prefix): raise ContentValidationError( f"Active definition {attribute_key!r} does not belong to canonical prefix " f"{definition_set.attribute_prefix_code!r}" ) code = attribute_key.rsplit(".", 1)[-1].strip() if not code: raise ContentValidationError( f"Definition {row['id']} has invalid canonical attribute_key {attribute_key!r}" ) metadata = row["metadata"] or {} by_id[row["id"]] = AttributeDefinition( id=row["id"], definition_set_id=row["attribute_definition_set_id"], code=code, attribute_key=attribute_key, attribute_label=row["attribute_label"], data_type=row["data_type"], definition_kind=row["definition_kind"], is_root=row["is_root"], is_required=row["is_required"], is_multivalue=row["is_multivalue"], allowed_values=row["allowed_values"], default_value=metadata.get("default"), sort_order=row["sort_order"], ) if not by_id: raise DefinitionNotFoundError( f"Definition set {definition_set.code!r} has no active attributes" ) member_result = await self._session.execute( text( f""" select parent_attribute_definition_id, child_attribute_definition_id, sort_order, is_required from {self._schema}.attribute_definition_members where parent_attribute_definition_id = any(:definition_ids) order by parent_attribute_definition_id, sort_order, child_attribute_definition_id """ ), {"definition_ids": list(by_id.keys())}, ) children_by_parent: dict[UUID, dict[str, AttributeDefinition]] = {} child_ids: set[UUID] = set() for row in member_result.mappings(): parent_id = row["parent_attribute_definition_id"] child_id = row["child_attribute_definition_id"] parent = by_id.get(parent_id) child = by_id.get(child_id) if parent is None: continue if child is None: raise ContentValidationError( "Definition member references child outside active definition set: " f"parent={parent.attribute_key!r}, child_id={child_id}" ) child_ids.add(child_id) bucket = children_by_parent.setdefault(parent_id, {}) if child.code in bucket: raise ContentValidationError( f"Duplicate child code {child.code!r} beneath {parent.attribute_key!r}" ) bucket[child.code] = child roots: dict[str, AttributeDefinition] = {} for definition in by_id.values(): if not definition.is_root: continue if definition.id in child_ids: raise ContentValidationError( f"Definition is marked root but also appears as child: {definition.attribute_key!r}" ) if definition.code in roots: raise ContentValidationError( f"Duplicate root code {definition.code!r} in definition set {definition_set.code!r}" ) roots[definition.code] = definition if not roots: raise ContentValidationError( f"Definition set {definition_set.code!r} has no active root definitions" ) return DefinitionGraph( definition_set=definition_set, roots=roots, children_by_parent=children_by_parent, ) async def _seed_row( self, *, row_number: int, graph: DefinitionGraph, content: Mapping[str, Any], publish: bool, ) -> ContentSeedResult: definition_set = graph.definition_set validate_object_input( definitions=graph.roots, content=content, reserved_fields=self.RESERVED_ROOT_FIELDS, ) source_component_raw = content.get("code") if not isinstance(source_component_raw, str) or not source_component_raw.strip(): raise ContentValidationError( "Each content row must provide a non-empty string 'code'. " "The code is the stable authoring identity used to derive source_key; " "display fields such as name/title must never define identity." ) source_component_raw = source_component_raw.strip() source_component = slugify(source_component_raw) if not source_component: raise ContentValidationError( "Content 'code' becomes empty after canonicalization" ) try: source_key = build_source_key( template_code=definition_set.attribute_prefix_code, source_code=source_component_raw, ) except Exception as exc: raise ContentValidationError( f"Unable to build canonical source_key: {exc}" ) from exc title = str(content.get("title") or content.get("name") or source_component_raw).strip() slug = str( content.get("slug") or f"{slugify(definition_set.attribute_prefix_code)}-{slugify(title)}" ).strip() if not slug: raise ContentValidationError("Unable to derive a non-empty slug") metadata = dict(content.get("metadata") or {}) metadata["definition_set_code"] = definition_set.code metadata["attribute_prefix_code"] = definition_set.attribute_prefix_code content_id, created = await self._upsert_content_item( definition_set=definition_set, source_key=source_key, title=title, slug=slug, summary=content.get("summary"), metadata=metadata, ) await self._session.execute( text( f"delete from {self._schema}.content_attributes where content_id = :content_id" ), {"content_id": content_id}, ) written = await self._seed_value_mapping( content_id=content_id, definitions=graph.roots, values=content, graph=graph, parent_value_id=None, depth=0, reserved_fields=self.RESERVED_ROOT_FIELDS, ) status = "draft" if publish: updated = await self._session.execute( text( f""" update {self._schema}.content_items set status = 'published', published_at = coalesce(published_at, now()), updated_at = now() where id = :content_id and status = 'draft' returning id """ ), {"content_id": content_id}, ) if updated.scalar_one_or_none() is None: raise ContentValidationError( f"Unable to publish content {content_id}; expected draft status" ) status = "published" return ContentSeedResult( row_number=row_number, content_id=content_id, source_key=source_key, slug=slug, created=created, updated=not created, attribute_rows_written=written, status=status, ) async def _seed_value_mapping( self, *, content_id: UUID, definitions: Mapping[str, AttributeDefinition], values: Mapping[str, Any], graph: DefinitionGraph, parent_value_id: UUID | None, depth: int, reserved_fields: set[str] | None = None, ) -> int: if depth > self._max_depth: raise ContentValidationError( f"Maximum attribute depth {self._max_depth} exceeded" ) validate_object_input( definitions=definitions, content=values, reserved_fields=reserved_fields or set(), ) written = 0 for definition in sorted( definitions.values(), key=lambda item: (item.sort_order, item.code) ): if definition.code in values: raw_value = values[definition.code] else: raw_value = definition.default_value if raw_value is None: if definition.is_required: raise ContentValidationError( f"Required attribute {definition.code!r} is missing" ) continue if definition.is_multivalue: if not isinstance(raw_value, list): raise ContentValidationError( f"Multivalue attribute {definition.code!r} requires an array" ) for value_sort_order, item in enumerate(raw_value): written += await self._seed_single_definition_value( content_id=content_id, definition=definition, raw_value=item, graph=graph, parent_value_id=parent_value_id, sort_order=value_sort_order, depth=depth, ) else: written += await self._seed_single_definition_value( content_id=content_id, definition=definition, raw_value=raw_value, graph=graph, parent_value_id=parent_value_id, sort_order=0, depth=depth, ) return written async def _seed_single_definition_value( self, *, content_id: UUID, definition: AttributeDefinition, raw_value: Any, graph: DefinitionGraph, parent_value_id: UUID | None, sort_order: int, depth: int, ) -> int: if definition.definition_kind == "scalar": converted = convert_scalar_value(definition=definition, value=raw_value) await self._insert_scalar_attribute( content_id=content_id, definition=definition, value=converted, parent_value_id=parent_value_id, sort_order=sort_order, ) return 1 if definition.definition_kind != "object": raise ContentValidationError( f"Unsupported definition_kind {definition.definition_kind!r}" ) if not isinstance(raw_value, Mapping): raise ContentValidationError( f"Object attribute {definition.code!r} requires a JSON object" ) object_value_id = uuid4() await self._session.execute( text( f""" insert into {self._schema}.content_attributes ( id, content_id, attribute_definition_id, parent_attribute_value_id, sort_order ) values ( :id, :content_id, :definition_id, :parent_value_id, :sort_order ) """ ), { "id": object_value_id, "content_id": content_id, "definition_id": definition.id, "parent_value_id": parent_value_id, "sort_order": sort_order, }, ) children = graph.children_by_parent.get(definition.id, {}) if not children: raise ContentValidationError( f"Object definition has no active members: {definition.attribute_key!r}" ) child_count = await self._seed_value_mapping( content_id=content_id, definitions=children, values=raw_value, graph=graph, parent_value_id=object_value_id, depth=depth + 1, reserved_fields=set(), ) return 1 + child_count async def _upsert_content_item( self, *, definition_set: DefinitionSet, source_key: str, title: str, slug: str, summary: str | None, metadata: Mapping[str, Any], ) -> tuple[UUID, bool]: existing = await self._session.execute( text( f""" select id, status, attribute_definition_set_id from {self._schema}.content_items where source_key = :source_key for update """ ), {"source_key": source_key}, ) existing_row = existing.mappings().one_or_none() if existing_row is not None: existing_id = existing_row["id"] existing_status = str(existing_row["status"]) if existing_status != "draft": raise ContentValidationError( f"Refusing to overwrite existing {existing_status!r} content for " f"source_key={source_key!r}; return it to draft first" ) existing_definition_set_id = existing_row["attribute_definition_set_id"] if ( existing_definition_set_id is not None and existing_definition_set_id != definition_set.id ): raise ContentValidationError( f"Existing source_key belongs to a different definition set: {source_key!r}" ) await self._session.execute( text( f""" update {self._schema}.content_items set content_kind = cast(:content_kind as {self._schema}.content_kind_enum), attribute_definition_set_id = :definition_set_id, title = :title, slug = :slug, summary = :summary, metadata = cast(:metadata as jsonb), version_no = version_no + 1, updated_at = now() where id = :content_id """ ), { "content_id": existing_id, "definition_set_id": definition_set.id, "content_kind": definition_set.content_kind, "title": title, "slug": slug, "summary": summary, "metadata": json.dumps(dict(metadata)), }, ) return existing_id, False content_id = uuid4() await self._session.execute( text( f""" insert into {self._schema}.content_items ( id, content_kind, attribute_definition_set_id, title, slug, source_key, summary, status, published_at, metadata ) values ( :id, cast(:content_kind as {self._schema}.content_kind_enum), :definition_set_id, :title, :slug, :source_key, :summary, 'draft', null, cast(:metadata as jsonb) ) """ ), { "id": content_id, "definition_set_id": definition_set.id, "content_kind": definition_set.content_kind, "title": title, "slug": slug, "source_key": source_key, "summary": summary, "metadata": json.dumps(dict(metadata)), }, ) return content_id, True async def _insert_scalar_attribute( self, *, content_id: UUID, definition: AttributeDefinition, value: Any, parent_value_id: UUID | None, sort_order: int, ) -> None: params: dict[str, Any] = { "content_id": content_id, "definition_id": definition.id, "parent_value_id": parent_value_id, "value_text": None, "value_number": None, "value_boolean": None, "value_date": None, "value_json": None, "media_asset_id": None, "sort_order": sort_order, } if definition.data_type in {"text", "rich_text"}: params["value_text"] = value elif definition.data_type == "number": params["value_number"] = value elif definition.data_type == "boolean": params["value_boolean"] = value elif definition.data_type == "date": params["value_date"] = value elif definition.data_type == "json": params["value_json"] = json.dumps(value) elif definition.data_type == "media": params["media_asset_id"] = value else: raise ContentValidationError( f"Unsupported data type {definition.data_type!r}" ) await self._session.execute( text( f""" insert into {self._schema}.content_attributes ( content_id, attribute_definition_id, parent_attribute_value_id, value_text, value_number, value_boolean, value_date, value_json, media_asset_id, sort_order ) values ( :content_id, :definition_id, :parent_value_id, :value_text, :value_number, :value_boolean, :value_date, cast(:value_json as jsonb), :media_asset_id, :sort_order ) """ ), params, )