"""Node-scoped material bindings for the existing gradual workflow. The planning-stage ``material_bind`` node remains the workflow-wide default. This service adds a small override on each currently writable image node so a user can add or remove references between generation rounds without creating a parallel workflow or copying material-library records. """ from __future__ import annotations from copy import deepcopy from datetime import UTC, datetime import re from typing import Any from backend.dto.common import ApiError, ErrorCode from backend.services.branch_lineage_service import workflow_metadata_for_branch from backend.services.material_binding_schema_service import ( NODE_MATERIAL_BINDING_METADATA_KEY, NODE_MATERIAL_BINDING_SCHEMA_VERSION, material_bindings_for_node, ) from backend.services.material_catalog_resolver import MaterialCatalogResolver from backend.services.resource_access_service import ResourceAccessService from backend.services.workflow_material_snapshot_service import ( normalize_persistent_reference_uri, normalize_temporary_references, ) from backend.services.workflow_service import WorkflowService from core.identity import RequestContext from database.repositories.material_repository import MaterialRepository from database.repositories.workflow_round_repository import WorkflowRoundRepository from engines.character_flow import canonical_gradual_node_key from core.text_utils import optional_text as _optional_text WORKFLOW_IMAGE_NODE_KEYS = frozenset( { "headshot", "upper_body", "lower_body", "full_body", "turnaround", "design_sheet", "style_lock", } ) _RETURN_VIEW_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$") _STRENGTHS: dict[str, tuple[str, float]] = { "strong": ("strong", 0.85), "high": ("strong", 0.85), "medium": ("medium", 0.55), "mid": ("medium", 0.55), "weak": ("weak", 0.30), "low": ("weak", 0.30), } class WorkflowNodeMaterialService: def __init__( self, workflow_service: WorkflowService, material_repository: MaterialRepository | MaterialCatalogResolver, *, round_repository: WorkflowRoundRepository | None = None, access_service: ResourceAccessService | None = None, ): self.workflow_service = workflow_service self.materials = material_repository self.rounds = round_repository self.access = access_service def get_node_bindings( self, node_id: str, ctx: RequestContext, *, navigation_context: dict[str, Any] | None = None, ) -> dict[str, Any]: node, workflow = self._require_target(node_id, ctx) branch_nodes = self.workflow_service.workflow_repository.list_nodes( workflow.workflow_id, branch_name=node.branch_name, ) branch_metadata = workflow_metadata_for_branch(workflow.metadata, node.branch_name) material_bindings = material_bindings_for_node(branch_metadata, node, branch_nodes) stored_navigation = ( material_bindings.get("navigation_context") if isinstance(material_bindings.get("navigation_context"), dict) else {} ) navigation = self._navigation_context( workflow_id=workflow.workflow_id, branch_name=node.branch_name, node_id=node.node_id, source=navigation_context if isinstance(navigation_context, dict) else stored_navigation, ) writable, lock = self._write_state(node) state = ( deepcopy(node.metadata.get(NODE_MATERIAL_BINDING_METADATA_KEY)) if isinstance(node.metadata, dict) and isinstance(node.metadata.get(NODE_MATERIAL_BINDING_METADATA_KEY), dict) else None ) return { **navigation, "navigation_context": navigation, "workflow_status": workflow.status, "node_key": node.node_key, "node_title": node.title, "node_status": node.status, "writable": writable, "lock": lock, "material_bindings": material_bindings, "temporary_references": deepcopy(material_bindings.get("temporary_references") or []), "binding_state": state, } def save_node_bindings( self, node_id: str, payload: dict[str, Any], ctx: RequestContext, ) -> dict[str, Any]: node, workflow = self._require_target(node_id, ctx) # ``completed`` means a candidate round has finished, not that the # stage was finally adopted. The progression guard correctly permits # that current node while still rejecting selected ancestors/future # nodes and archived workflows. self.workflow_service.ensure_node_action_allowed(node.node_id, "update", node=node) current = self.get_node_bindings(node.node_id, ctx) current_bindings = ( current.get("material_bindings") if isinstance(current.get("material_bindings"), dict) else {} ) source, selection_explicit = _binding_source(payload) if selection_explicit: selected_material_ids = _selected_material_ids(source) else: selected_material_ids = _selected_material_ids(current_bindings) input_bindings = _binding_input_index(source if selection_explicit else current_bindings) active_bindings = [ self._material_binding(material_id, node, input_bindings.get(material_id, {})) for material_id in selected_material_ids ] temporary_explicit, raw_temporary = _temporary_reference_input(payload, source) temporary_references = normalize_temporary_references( raw_temporary if temporary_explicit else current_bindings.get("temporary_references") or [] ) navigation_source = ( payload.get("navigation_context") if isinstance(payload.get("navigation_context"), dict) else { key: payload.get(key) for key in ("workflow_id", "branch_name", "node_id", "round_id", "return_view") if key in payload } ) if not navigation_source: navigation_source = current.get("navigation_context") or {} navigation = self._navigation_context( workflow_id=workflow.workflow_id, branch_name=node.branch_name, node_id=node.node_id, source=navigation_source, ) state = { "schema_version": NODE_MATERIAL_BINDING_SCHEMA_VERSION, "workflow_id": workflow.workflow_id, "branch_name": node.branch_name, "node_id": node.node_id, "selected_material_ids": selected_material_ids, "active_bindings": active_bindings, "temporary_references": temporary_references, "navigation_context": navigation, "updated_at": datetime.now(UTC).isoformat(), "updated_by": ctx.actor_id or "system", } before_state = ( deepcopy(node.metadata.get(NODE_MATERIAL_BINDING_METADATA_KEY)) if isinstance(node.metadata, dict) else None ) updated = self.workflow_service.workflow_repository.update_node( node.node_id, { "metadata": { **(node.metadata if isinstance(node.metadata, dict) else {}), NODE_MATERIAL_BINDING_METADATA_KEY: state, } }, ) if updated is None: raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "node not found", {"node_id": node.node_id}) self.workflow_service.audit_service.record( ctx=ctx, action="update_workflow_node_material_bindings", target_type="workflow_node", target_id=node.node_id, before_snapshot={"material_bindings": before_state}, after_snapshot={"material_bindings": state}, ) if self.workflow_service.event_bus: self.workflow_service.event_bus.publish( "workflow.node_material_bindings_updated", { "workflow_id": workflow.workflow_id, "branch_name": node.branch_name, "node_id": node.node_id, "material_count": len(selected_material_ids), "temporary_reference_count": len(temporary_references), }, ) return self.get_node_bindings( updated.node_id, ctx, navigation_context=navigation, ) def _require_target(self, node_id: str, ctx: RequestContext): if self.access is not None: node = self.access.require_node(node_id, ctx) else: node = self.workflow_service.get_node(node_id) workflow_for_owner = self.workflow_service.workflow_repository.get_workflow(node.workflow_id) profile = ( self.workflow_service.profile_repository.get(workflow_for_owner.profile_id) if workflow_for_owner is not None else None ) owner_id = getattr(profile, "owner_user_id", None) if ( workflow_for_owner is None or profile is None or not ( ctx.has_permission("can_manage_all_profiles") or ctx.has_permission("*") or (ctx.actor_id and owner_id and ctx.actor_id == owner_id) ) ): raise ApiError( ErrorCode.RESOURCE_NOT_FOUND, "workflow node not found", {"resource_id": node_id}, ) workflow = self.workflow_service.workflow_repository.get_workflow(node.workflow_id) if workflow is None: raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "workflow not found", {"workflow_id": node.workflow_id}) canonical_key = canonical_gradual_node_key(node.node_key) if ( workflow.workflow_type != "character_gradual" or node.node_type != "generation" or canonical_key not in WORKFLOW_IMAGE_NODE_KEYS ): raise ApiError( ErrorCode.VALIDATION_FAILED, "node material bindings are available only on detailed-workflow image stages", { "workflow_id": workflow.workflow_id, "workflow_type": workflow.workflow_type, "node_id": node.node_id, "node_key": node.node_key, "node_type": node.node_type, "allowed_node_keys": sorted(WORKFLOW_IMAGE_NODE_KEYS), }, ) return node, workflow def _write_state(self, node) -> tuple[bool, dict[str, Any] | None]: try: self.workflow_service.ensure_node_action_allowed(node.node_id, "update", node=node) except ApiError as exc: return False, { "error_code": str(exc.error_code), "message": exc.message, "details": deepcopy(exc.details), } return True, None def _material_binding(self, material_id: str, node, source: dict[str, Any]) -> dict[str, Any]: material = self.materials.get_material(material_id) if material is None or material.recognition_status == "archived": raise ApiError( ErrorCode.RESOURCE_NOT_FOUND, "workflow reference material does not exist", {"material_id": material_id, "node_id": node.node_id}, ) if material.recognition_status != "confirmed": raise ApiError( ErrorCode.VALIDATION_FAILED, "workflow reference material must be recognized and confirmed before use", { "material_id": material_id, "recognition_status": material.recognition_status, "required_action": "recognize_and_confirm_material", }, ) normalize_persistent_reference_uri(material.image_uri, field=f"materials[{material_id}].image_uri") category = self.materials.get_category(material.category_id) if material.category_id else None material_source = source.get("material") if isinstance(source.get("material"), dict) else {} strength = _reference_strength(source.get("reference_strength")) colors = _string_list(material.metadata.get("colors")) if isinstance(material.metadata, dict) else [] catalog_metadata = material.metadata if isinstance(material.metadata, dict) else {} return { "id": str(source.get("id") or f"node_material_{material_id}"), "category": str( source.get("category") or (category.category_type if category is not None else "material") ), "use_reference": True, "required": bool(source.get("required")), "status": "ready", "material": { "material_id": material.material_id, "label": material.display_name, "group": category.name if category is not None else None, "prompt": material.prompt or material_source.get("prompt"), "colors": colors, "library_kind": catalog_metadata.get("library_kind", "standard"), "priority_class": catalog_metadata.get("priority_class", "standard"), "material_priority": catalog_metadata.get("material_priority", 0), "verification": deepcopy(catalog_metadata.get("verification") or {}), }, "target_stages": [], "target_node_keys": [canonical_gradual_node_key(node.node_key)], "inheritance_rule": "node-scoped explicit reference", "reference_strength": strength, "generation_params": { "reference_policy": "explicit_only", "reference_strength": strength["key"], "reference_weight": strength["weight"], }, "source": "node_midflow_material_binding", } def _navigation_context( self, *, workflow_id: str, branch_name: str, node_id: str, source: dict[str, Any] | None, ) -> dict[str, Any]: payload = source if isinstance(source, dict) else {} for field, expected in ( ("workflow_id", workflow_id), ("branch_name", branch_name), ("node_id", node_id), ): supplied = str(payload.get(field) or "").strip() if supplied and supplied != expected: raise ApiError( ErrorCode.VALIDATION_FAILED, "material navigation context does not match the active workflow stage", {"field": field, "expected": expected, "actual": supplied}, ) round_id = _optional_text(payload.get("round_id")) if round_id: if self.rounds is None: raise ApiError( ErrorCode.VALIDATION_FAILED, "round navigation cannot be validated", {"round_id": round_id}, ) round_record = self.rounds.get_round(round_id) if round_record is None: raise ApiError( ErrorCode.RESOURCE_NOT_FOUND, "workflow generation round not found", {"round_id": round_id}, ) if ( round_record.workflow_id != workflow_id or round_record.branch_name != branch_name or round_record.node_id != node_id ): raise ApiError( ErrorCode.VALIDATION_FAILED, "round navigation belongs to another workflow stage", { "reason": "workflow_material_round_context_mismatch", "round_id": round_id, "workflow_id": workflow_id, "branch_name": branch_name, "node_id": node_id, }, ) return_view = _optional_text(payload.get("return_view")) or "generate" if not _RETURN_VIEW_RE.fullmatch(return_view): raise ApiError( ErrorCode.VALIDATION_FAILED, "return_view must be a simple application view name", {"field": "return_view"}, ) return { "workflow_id": workflow_id, "branch_name": branch_name, "node_id": node_id, "round_id": round_id, "return_view": return_view, } def _binding_source(payload: dict[str, Any]) -> tuple[dict[str, Any], bool]: nested = payload.get("material_bindings") source = nested if isinstance(nested, dict) else payload explicit_fields = { "selected_material_ids", "material_ids", "active_bindings", "rules", "generation_params", } return source, any(field in source for field in explicit_fields) def _selected_material_ids(source: dict[str, Any]) -> list[str]: if "selected_material_ids" in source: return _unique_texts(source.get("selected_material_ids")) if "material_ids" in source: return _unique_texts(source.get("material_ids")) generation_params = source.get("generation_params") if isinstance(generation_params, dict) and "reference_material_ids" in generation_params: return _unique_texts(generation_params.get("reference_material_ids")) values: list[Any] = [] for key in ("active_bindings", "rules"): for item in source.get(key, []) if isinstance(source.get(key), list) else []: if not isinstance(item, dict) or item.get("use_reference") is False: continue material = item.get("material") if isinstance(item.get("material"), dict) else {} values.append(material.get("material_id") or item.get("material_id")) return _unique_texts(values) def _binding_input_index(source: dict[str, Any]) -> dict[str, dict[str, Any]]: result: dict[str, dict[str, Any]] = {} for key in ("active_bindings", "rules"): values = source.get(key) if not isinstance(values, list): continue for item in values: if not isinstance(item, dict): continue material = item.get("material") if isinstance(item.get("material"), dict) else {} material_id = _optional_text(material.get("material_id") or item.get("material_id")) if material_id: result[material_id] = item return result def _temporary_reference_input( payload: dict[str, Any], source: dict[str, Any], ) -> tuple[bool, Any]: if "temporary_references" in payload: return True, payload.get("temporary_references") if "temporary_references" in source: return True, source.get("temporary_references") return False, None def _reference_strength(value: Any) -> dict[str, Any]: if isinstance(value, dict): key = str(value.get("key") or value.get("label") or "medium").strip().lower() default_key, default_weight = _STRENGTHS.get(key, ("medium", 0.55)) try: weight = float(value.get("weight", default_weight)) except (TypeError, ValueError): weight = default_weight return { "label": str(value.get("label") or default_key), "key": default_key, "weight": min(max(weight, 0.0), 1.0), } key = str(value or "medium").strip().lower() normalized_key, weight = _STRENGTHS.get(key, ("medium", 0.55)) return {"label": normalized_key, "key": normalized_key, "weight": weight} def _unique_texts(value: Any) -> list[str]: values = value if isinstance(value, (list, tuple, set)) else [value] result: list[str] = [] for item in values: text = str(item or "").strip() if text and text not in result: result.append(text) return result def _string_list(value: Any) -> list[str]: return _unique_texts(value) if value is not None else []