from __future__ import annotations import re from pathlib import Path def require_non_empty_string(value: str, field_name: str) -> str: value = value.strip() if not value: raise ValueError(f"{field_name} must not be empty") return value def slugify(value: str) -> str: value = re.sub(r"[^a-z0-9]+", "-", value.strip().lower()) return value.strip("-") def build_source_key(*, template_code: str, source_code: str) -> str: normalized_template = require_non_empty_string( template_code, "template_code" ).lower() normalized_source_code = require_non_empty_string( source_code, "source_code" ) stable_component = slugify(normalized_source_code) if not stable_component: raise ValueError("source_code becomes empty after canonicalization") return f"{normalized_template}:{stable_component}" def canonical_media_filename( *, source_code: str, usage_type: str, ordinal: int, extension: str, ) -> str: """Build a template-independent canonical filename for one media asset.""" source_component = slugify(source_code) if not source_component: raise ValueError("source_code becomes empty after canonicalization") usage_component = slugify(usage_type) if not usage_component: raise ValueError("usage_type becomes empty after canonicalization") extension = extension.lower() if not extension.startswith("."): extension = f".{extension}" return f"{source_component}--{usage_component}--{ordinal:02d}{extension}" def build_storage_key( *, module_code: str, filename: str, ) -> str: """ Build a module-scoped, template-independent object-storage key. The same physical media file can therefore be associated with content from multiple templates without creating a second storage object. """ module_component = require_non_empty_string( module_code, "module_code" ).lower() file_component = Path(filename).name if not file_component: raise ValueError("filename must not be empty") return f"images/{module_component}/{file_component}"