Skip to content

Home Information - Your home, your data, organized.

Python
40.4 KB
Raw Blame
"""
Entity placement: putting entities into LocationViews.

"Placement" is the union of (a) deciding what an entity should look
like in a view (a centered icon, a default path), (b) persisting the
chosen ``EntityPosition`` / ``EntityPath`` row, and (c) linking the
entity to the ``LocationView`` via an ``EntityView``. All three are
the responsibility of this module.

Two collaborating classes:

* ``EntityPlacementCalculator`` — orchestrates per-entity shape
  selection (Point vs Path), delegating "where in the SVG" to
  ``PositionGeometry`` and "how a path looks" to ``PathGeometry``.
  Performs no DB writes.

* ``EntityPlacer`` — DB-touching placer. Accepts either a
  pre-computed ``PlacementShape`` (e.g., from Phase 3's dispatcher
  modal that lays out an entire sync result group at once) or
  derives one via the calculator. Persists the result, links the
  entity to the view, manages delegates, owns un-place / toggle
  counterparts, and runs entity-type transitions.

Known limitation (carried over from earlier code, not introduced by
this module): when an entity carrying delegate entities is placed
into a view, the delegates are placed at the viewbox center
without any spread. Multiple delegates therefore overlap. Phase 3
inherits this behavior; revisit when it bites.
"""

from dataclasses import dataclass, field
from decimal import Decimal
import logging
from typing import Callable, Dict, List, Optional, Tuple, Union

from django.db import transaction

from hi.apps.common.svg_models import SvgViewBox
from hi.apps.entity.edit.forms import EntityPositionForm
from hi.apps.entity.enums import (
    EntityGroupType,
    EntityType,
    EntityTransitionType,
)
from hi.apps.location.models import Location, LocationView
from hi.apps.location.path_geometry import PathGeometry
from hi.apps.location.position_geometry import PositionGeometry
from hi.hi_styles import EntityIconDirection, EntityStyle

from .entity_pairing_manager import EntityPairingManager
from .models import (
    Entity,
    EntityPath,
    EntityPosition,
    EntityView,
)

logger = logging.getLogger(__name__)


# Default heading the placement modal renders above its group list.
# "Type" reads naturally for both leaf EntityType and rollup
# EntityGroupType — they're item types at different resolutions.
# Integrations override on a per-placement-input basis when they
# group by a different dimension (location, tag, etc.).
PLACEMENT_DEFAULT_HEADING = 'Item Type'


@dataclass(frozen=True)
class PlacementPoint:
    """SVG icon placement: center-of-icon coordinates plus scale."""
    svg_x: float
    svg_y: float
    svg_scale: Decimal


@dataclass(frozen=True)
class PlacementPath:
    """SVG path placement: a fully-formed path string already centered
    and sized for the chosen view."""
    svg_path: str


PlacementShape = Union[PlacementPoint, PlacementPath]


@dataclass
class EntityPlacementItem:
    """A single entity destined for placement.

    ``key`` is a stable identifier the dispatcher modal uses to
    address this item across form turns; suppliers typically derive
    it from a per-entity integration_key, but the placement layer
    only requires uniqueness within a placement input.
    """
    key: str
    label: str
    entity: Entity


@dataclass
class EntityPlacementGroup:
    """A supplier-defined grouping of items for the dispatcher modal.

    Suppliers create groups when their domain has a meaningful
    grouping notion (HASS by entity_type, ZM monitors). The
    dispatcher presents groups verbatim.
    """
    label: str
    items: List[EntityPlacementItem] = field(default_factory=list)


@dataclass
class EntityPlacementInput:
    """The shape the dispatcher modal needs: groups and ungrouped
    items to choose placements for.

    Producible from any source — a freshly-run integration sync, a
    "place unplaced items" recovery feature, or any future bulk-
    placement flow. The placement layer does not know what produced
    its input; suppliers do not know how the dispatcher renders or
    applies the result.

    ``heading`` is the column-heading label the modal renders
    above the group list. Suppliers set it to name the grouping
    dimension (e.g., "HomeBox Location" or "Type"). Defaults to
    ``PLACEMENT_DEFAULT_HEADING``.
    """
    groups: List[EntityPlacementGroup] = field(default_factory=list)
    ungrouped_items: List[EntityPlacementItem] = field(default_factory=list)
    heading: str = PLACEMENT_DEFAULT_HEADING

    def is_empty(self) -> bool:
        if self.ungrouped_items:
            return False
        return not any( group.items for group in self.groups )

    def all_entity_ids(self) -> 'List[int]':
        """Flatten the entity ids from groups + ungrouped items.
        Used by callers that need to thread the placement scope
        through a URL or session — e.g., the sync-result CTA
        passing the just-imported entity ids to the dispatcher
        view so it scopes to those entities rather than all
        unplaced ones for the integration."""
        ids = []
        for group in self.groups:
            for item in group.items:
                ids.append( item.entity.id )
        for item in self.ungrouped_items:
            ids.append( item.entity.id )
        return ids


@dataclass(frozen=True)
class PlacementDecision:
    """One entity → placement-target assignment chosen by the operator.

    Targets are mutually exclusive: at most one of ``location_view``
    and ``collection`` is set. Both None means the operator skipped
    placement for this entity; skipped decisions are filtered out
    before placement and counted toward the placement outcome's
    ``skipped_entity_count``.
    """
    entity: Entity
    location_view: Optional[LocationView] = None
    collection: 'Optional[object]' = None  # Collection; forward-decl

    @property
    def is_skip(self) -> bool:
        return self.location_view is None and self.collection is None

    @property
    def is_view(self) -> bool:
        return self.location_view is not None

    @property
    def is_collection(self) -> bool:
        return self.collection is not None


@dataclass(frozen=True)
class PlacementSummary:
    """One affected target + how many entities the bulk placer
    placed into it. Targets are mutually exclusive: exactly one of
    ``location_view`` or ``collection`` is set."""
    placed_entity_count: int
    location_view: Optional[LocationView] = None
    collection: 'Optional[object]' = None  # Collection; forward-decl

    @property
    def is_view(self) -> bool:
        return self.location_view is not None

    @property
    def is_collection(self) -> bool:
        return self.collection is not None

    @property
    def target_name(self) -> str:
        if self.location_view is not None:
            return self.location_view.name
        return self.collection.name


@dataclass
class PlacementOutcome:
    """Result of one bulk placement. Drives the post-dispatch modal:
    per-target summary lines, primary 'Refine'/'Review' button
    selection, the skipped count when present.

    Lives in the placement layer rather than an integration layer
    because the shape is supplier-agnostic — any future bulk-
    placement flow that accepts placement decisions and applies
    them produces this outcome.
    """
    summaries: List[PlacementSummary] = field(default_factory=list)
    skipped_entity_count: int = 0

    @property
    def total_placed(self) -> int:
        return sum(s.placed_entity_count for s in self.summaries)

    @property
    def primary_summary(self) -> Optional[PlacementSummary]:
        """Highest-count summary, with view-targeted summaries
        preferred over collection-targeted ones. The post-dispatch
        modal's primary action is REFINE for views (drag entities
        into spatial position) — meaningless for collections — so
        when any view target was used, that's the primary slot.
        Only when every placement landed in a Collection does the
        primary become a Collection (with a REVIEW link instead of
        REFINE)."""
        view_summaries = [s for s in self.summaries if s.is_view]
        if view_summaries:
            return max(view_summaries, key=lambda s: s.placed_entity_count)
        if self.summaries:
            return max(self.summaries, key=lambda s: s.placed_entity_count)
        return None

    @property
    def secondary_summaries(self) -> List[PlacementSummary]:
        """All summaries except the primary, in input order."""
        primary = self.primary_summary
        if primary is None:
            return []
        result = []
        skipped = False
        for summary in self.summaries:
            if not skipped and summary is primary:
                skipped = True
                continue
            result.append(summary)
        return result


class PlacementInputBuilder:
    """Reusable bucket-and-group builders for ``EntityPlacementInput``.

    Both the framework default and integration-specific groupers
    (e.g. HomeBox's Location/Tag/Type pipeline) route through here
    so the bucketing semantics — alphabetical group ordering, the
    no-signal handling, the heading wiring — stay in one place.
    """

    @staticmethod
    def by_label_fn(
            entities       : List['Entity'],
            item_key_fn    : Callable[['Entity'], str],
            label_fn       : Callable[['Entity'], Optional[str]],
            heading        : str,
            fallback_label : Optional[str] = None,
    ) -> 'EntityPlacementInput':
        """Bucket entities by ``label_fn(entity)``.

        Entities for which ``label_fn`` returns None land in a
        labeled fallback group when ``fallback_label`` is set,
        else in ``ungrouped_items``. Named groups are emitted in
        alphabetical label order; the fallback group is appended
        last when present.
        """
        label_to_items: Dict[str, List[EntityPlacementItem]] = {}
        fallback_items: List[EntityPlacementItem] = []
        ungrouped_items: List[EntityPlacementItem] = []
        for entity in entities:
            item = EntityPlacementItem(
                key    = item_key_fn( entity ),
                label  = entity.name,
                entity = entity,
            )
            label = label_fn( entity )
            if label is None:
                if fallback_label is not None:
                    fallback_items.append( item )
                else:
                    ungrouped_items.append( item )
                continue
            label_to_items.setdefault( label, [] ).append( item )

        groups = [
            EntityPlacementGroup( label = label, items = label_to_items[ label ] )
            for label in sorted( label_to_items.keys() )
        ]
        if fallback_items:
            groups.append(
                EntityPlacementGroup(
                    label = fallback_label,
                    items = fallback_items,
                )
            )
        return EntityPlacementInput(
            groups          = groups,
            ungrouped_items = ungrouped_items,
            heading         = heading,
        )

    @staticmethod
    def by_entity_type_group(
            entities    : List['Entity'],
            item_key_fn : Callable[['Entity'], str],
            heading     : str = PLACEMENT_DEFAULT_HEADING,
    ) -> 'EntityPlacementInput':
        """Default placement grouping: bucket entities by their
        ``EntityGroupType`` rollup label. The rollup avoids
        scattering a typical batch across many one- or two-item
        leaf-type buckets."""
        return PlacementInputBuilder.by_label_fn(
            entities    = entities,
            item_key_fn = item_key_fn,
            label_fn    = lambda e: EntityGroupType.from_entity_type(
                e.entity_type
            ).label,
            heading     = heading,
        )


class EntityPlacementService:
    """Bulk-placement operations: query candidate entities and apply
    a list of operator placement decisions. Supplier-agnostic; the
    integration sync flow and any future bulk-placement entry point
    (e.g., a 'place unplaced items' recovery feature) call into this.
    """

    @classmethod
    def query_unplaced_entities( cls,
                                 integration_id : Optional[str] = None,
                                 ) -> 'List[Entity]':
        """Entities that have neither an EntityView nor a
        CollectionEntity row — fully unplaced in the app. Optionally
        filtered to a single integration. Used by the dispatcher
        GET endpoint to seed the modal with what's left to place.

        Integration scoping uses ``with_integration_provenance`` so
        both active-Connect rows and imported / detached rows for
        the same integration are eligible — post-import placement
        and post-sync placement land on the same query."""
        if integration_id is not None:
            queryset = Entity.objects.with_integration_provenance(
                integration_id = integration_id,
            )
        else:
            queryset = Entity.objects.all()
        queryset = queryset.filter(
            entity_views__isnull = True,
            collections__isnull = True,
        )
        return list( queryset.distinct() )

    @classmethod
    def apply_decisions(
            cls,
            decisions : 'List[PlacementDecision]',
    ) -> PlacementOutcome:
        """Partition decisions by target (preserving first-seen
        order so the post-dispatch summary lists targets in the
        order the operator's choices produced them), invoke the
        right placement op per target type, and aggregate per-
        target counts into a PlacementOutcome.

        View targets go through ``EntityPlacer.place_entities_in_view``;
        Collection targets go through
        ``CollectionManager.add_entity_to_collection``."""
        from collections import OrderedDict
        from hi.apps.collection.collection_manager import CollectionManager

        outcome = PlacementOutcome()
        # Key by (kind, id) so views and collections occupy distinct
        # buckets even if their numeric ids overlap.
        by_target = OrderedDict()
        for decision in decisions:
            if decision.is_skip:
                outcome.skipped_entity_count += 1
                continue
            if decision.is_view:
                key = ('view', decision.location_view.id)
            else:
                key = ('collection', decision.collection.id)
            by_target.setdefault( key, [] ).append( decision )
            continue
        for (kind, _target_id), decision_list in by_target.items():
            entities = [ d.entity for d in decision_list ]
            if kind == 'view':
                location_view = decision_list[0].location_view
                EntityPlacer().place_entities_in_view(
                    entities = entities, location_view = location_view,
                )
                outcome.summaries.append( PlacementSummary(
                    placed_entity_count = len( entities ),
                    location_view = location_view,
                ) )
            else:  # collection
                collection = decision_list[0].collection
                for entity in entities:
                    CollectionManager().add_entity_to_collection(
                        entity = entity, collection = collection,
                    )
                outcome.summaries.append( PlacementSummary(
                    placed_entity_count = len( entities ),
                    collection = collection,
                ) )
            continue
        return outcome


class EntityPlacementCalculator:
    """Orchestrates per-entity shape selection against a fixed viewbox.
    Pure-functional; performs no DB writes and has no model coupling -
    constructed with the ``SvgViewBox`` to position/size against (the
    LocationView's stored geometry, or an override). The geometry math
    lives in ``PositionGeometry`` (where) and ``PathGeometry`` (how a
    path looks); this class branches on entity_type to decide which
    output shape applies.
    """

    def __init__( self, view_box : SvgViewBox ):
        self._view_box = view_box
        return

    @property
    def view_box( self ) -> SvgViewBox:
        return self._view_box

    def shape_for_entity( self, entity : Entity ) -> PlacementShape:
        """Return the placement shape for a single entity centered on
        the viewbox."""
        svg_x, svg_y = PositionGeometry.view_center( self._view_box )
        return self._shape_at_point( entity = entity, svg_x = svg_x, svg_y = svg_y )

    def shapes_for_entities( self,
                             entities       : List[Entity] ) -> List[PlacementShape]:
        """Return one shape per entity in input order. Single-entity
        input degenerates to ``shape_for_entity``. Larger groups get
        a centered grid; each entity's slot becomes either a Point
        (icon entities) or a Path centered on that slot (path
        entities)."""
        total = len( entities )
        if total == 0:
            return []
        if total == 1:
            return [ self.shape_for_entity( entity = entities[0] ) ]

        return [
            self._shape_at_grid_slot(
                entity = entity,
                grid_index = index,
                grid_total = total,
            )
            for index, entity in enumerate( entities )
        ]

    def default_icon_scale( self, entity : Entity ) -> Decimal:
        """Default scale for an icon entity. Delegates to
        ``PositionGeometry.default_icon_scale``."""
        return PositionGeometry.default_icon_scale(
            entity = entity, view_box = self._view_box )

    # ----- internal shape routing (no DB) -----

    def _shape_at_grid_slot( self,
                             entity         : Entity,
                             grid_index     : int,
                             grid_total     : int ) -> PlacementShape:
        svg_x, svg_y = PositionGeometry.grid_slot(
            view_box = self._view_box,
            grid_index = grid_index,
            grid_total = grid_total,
        )
        return self._shape_at_point( entity = entity, svg_x = svg_x, svg_y = svg_y )

    def _shape_at_point( self,
                         entity         : Entity,
                         svg_x          : float,
                         svg_y          : float ) -> PlacementShape:
        entity_type = entity.entity_type
        if entity_type.requires_path():
            svg_path = PathGeometry.create_default_path_string(
                view_box = self._view_box,
                is_path_closed = entity_type.requires_closed_path(),
                center_x = svg_x,
                center_y = svg_y,
                entity_type = entity_type,
            )
            return PlacementPath( svg_path = svg_path )

        return PlacementPoint(
            svg_x = svg_x,
            svg_y = svg_y,
            svg_scale = self.default_icon_scale( entity = entity ),
        )


class EntityPlacer:
    """DB-touching placement operations. Persists shapes computed by
    EntityPlacementCalculator and links entities into LocationViews.
    Pulls in delegate entities so callers don't have to. Also owns
    user-drawn-path persistence, edit-form construction, and
    entity-type transitions (icon ↔ path)."""

    @staticmethod
    def _calculator_for( location_view         : LocationView,
                         svg_view_box_override : Optional[SvgViewBox] = None
                         ) -> EntityPlacementCalculator:
        """Build a calculator bound to the geometry placement should use:
        the override viewbox when given (e.g. the user's current
        pan/zoom), otherwise the LocationView's stored viewbox. The real
        location_view is never handed to the calculator - it is only the
        linkage target for persisted rows."""
        view_box = ( svg_view_box_override if svg_view_box_override is not None
                     else location_view.svg_view_box )
        return EntityPlacementCalculator( view_box = view_box )

    def place_entity_in_view( self,
                              entity           : Entity,
                              location_view    : LocationView,
                              placement_shape  : Optional[PlacementShape] = None,
                              bulk_grid_index      : Optional[int]            = None,
                              bulk_grid_total      : Optional[int]            = None,
                              svg_view_box_override : Optional[SvgViewBox]    = None ):
        """Place a single entity into a location view, including its
        delegate entities. Idempotent: existing position/path/view rows
        are preserved.

        Three input modes for shape selection (in priority order):

        1. Caller provides ``placement_shape`` directly — used.
        2. Caller provides ``bulk_grid_index`` + ``bulk_grid_total``
           (legacy form-driven flow) — calculator picks the slot.
        3. Otherwise — calculator centers the shape on the viewbox.

        ``svg_view_box_override`` optionally overrides the geometry the
        calculator positions/sizes against (e.g. the user's current
        pan/zoom) without changing the linkage target. Ignored when
        ``placement_shape`` is given. Applies to modes (2) and (3);
        delegates still center on the same (possibly overridden) viewbox.

        Delegates always go through mode (3): each delegate is placed
        at the viewbox center. See module docstring on the
        delegate-overlap limitation.
        """
        # The calculator positions/sizes against the override viewbox when
        # given, else the view's stored viewbox; the real location_view is
        # only the linkage target for the persisted rows below.
        calculator = self._calculator_for( location_view, svg_view_box_override )

        with transaction.atomic():
            if not entity.entity_views.all().exists():
                delegate_entity_list = (
                    EntityPairingManager().get_delegate_entities_with_defaults(
                        entity = entity )
                )
            else:
                delegate_entity_list = (
                    EntityPairingManager().get_delegate_entities( entity = entity )
                )

            if placement_shape is None:
                placement_shape = self._derive_placement_shape(
                    calculator = calculator,
                    entity = entity,
                    bulk_grid_index = bulk_grid_index,
                    bulk_grid_total = bulk_grid_total,
                )
            self._create_entity_view(
                entity = entity,
                location_view = location_view,
                placement_shape = placement_shape,
            )
            for delegate_entity in delegate_entity_list:
                delegate_shape = self._build_delegate_shape(
                    calculator = calculator,
                    principal_entity = entity,
                    principal_shape = placement_shape,
                    delegate_entity = delegate_entity,
                )
                self._create_entity_view(
                    entity = delegate_entity,
                    location_view = location_view,
                    placement_shape = delegate_shape,
                )
                continue
        return

    # Apex offset along the principal's icon-facing direction, expressed
    # as a fraction of the icon's half-extent in that direction. 0.0 =
    # apex at icon center; 1.0 = apex at icon edge. Falls between for a
    # less-than-edge but past-center anchor.
    _COVERAGE_APEX_OFFSET_FRACTION = 0.75

    def _build_delegate_shape(
            self,
            calculator       : EntityPlacementCalculator,
            principal_entity : Entity,
            principal_shape  : PlacementShape,
            delegate_entity  : Entity,
    ) -> PlacementShape:
        """Compute the delegate's placement shape. Default is the
        calculator's centered default. When the principal is an icon
        entity whose source-icon facing direction is known and the
        delegate is an AREA, build a triangular coverage path with its
        apex anchored near the principal's position so the delegate
        visually reads as the principal's coverage cone."""
        default_shape = calculator.shape_for_entity( entity = delegate_entity )
        if delegate_entity.entity_type != EntityType.AREA:
            return default_shape
        if not isinstance( principal_shape, PlacementPoint ):
            return default_shape

        icon_direction = EntityStyle.get_icon_direction( principal_entity.entity_type )
        if icon_direction is EntityIconDirection.UNKNOWN:
            return default_shape

        dx, dy = icon_direction.value
        icon_viewbox = EntityStyle.get_svg_icon_viewbox( principal_entity.entity_type )

        # Icon's dimension along the facing direction. ``dx`` and ``dy``
        # are 0/±1 for cardinal directions so this picks the relevant
        # axis cleanly.
        facing_extent = ( abs( dx ) * icon_viewbox.width
                          + abs( dy ) * icon_viewbox.height )
        principal_scale = float( principal_shape.svg_scale )
        apex_offset = ( facing_extent / 2.0
                        * self._COVERAGE_APEX_OFFSET_FRACTION
                        * principal_scale )

        apex_x = float( principal_shape.svg_x ) + ( dx * apex_offset )
        apex_y = float( principal_shape.svg_y ) + ( dy * apex_offset )

        svg_path = PathGeometry.create_coverage_triangle_path_string(
            view_box = calculator.view_box,
            apex_x = apex_x,
            apex_y = apex_y,
            direction = icon_direction.value,
        )
        return PlacementPath( svg_path = svg_path )

    def place_entities_in_view( self,
                                entities       : List[Entity],
                                location_view  : LocationView ):
        """Place a group of entities into a location view in a single
        layout pass. Used by the post-sync dispatcher to position all
        items in a result group together. The grid is computed once
        across the entire group; per-entity delegates are placed by
        the single-entity flow."""
        shapes = self._calculator_for( location_view ).shapes_for_entities(
            entities = entities,
        )
        with transaction.atomic():
            for entity, shape in zip( entities, shapes ):
                self.place_entity_in_view(
                    entity = entity,
                    location_view = location_view,
                    placement_shape = shape,
                )
                continue
        return

    def toggle_entity_in_view( self,
                               entity         : Entity,
                               location_view  : LocationView ) -> bool:
        """Add the entity to the view if absent, or remove it if
        present. Returns True if the entity is now in the view, False
        otherwise."""
        try:
            self.unplace_entity_from_view(
                entity = entity, location_view = location_view )
            return False
        except EntityView.DoesNotExist:
            self.place_entity_in_view(
                entity = entity, location_view = location_view )
            return True

    def ensure_default_shape_persisted( self,
                                        entity         : Entity,
                                        location_view  : LocationView ):
        """Ensure the entity has either an EntityPosition or
        EntityPath row for the location, creating it with default
        placement if missing. Does NOT create an EntityView link.

        Used by entity-type transition flows that already have an
        EntityView and just need a shape row to exist (e.g., a type
        change to a path-based type when no path row exists yet)."""
        shape = self._calculator_for( location_view ).shape_for_entity(
            entity = entity,
        )
        self._persist_placement_shape(
            entity = entity,
            location_view = location_view,
            placement_shape = shape,
        )
        return

    def unplace_entity_from_view( self,
                                  entity         : Entity,
                                  location_view  : LocationView ):
        """Remove an entity (and its no-longer-needed delegates) from a
        location view. Raises ``EntityView.DoesNotExist`` if the entity
        is not in the view."""
        with transaction.atomic():
            self._delete_entity_view(
                entity = entity,
                location_view = location_view,
            )
            EntityPairingManager().remove_delegate_entities_from_view_if_needed(
                entity = entity,
                location_view = location_view,
            )
        return

    def set_entity_path( self,
                         entity_id     : int,
                         location      : Location,
                         svg_path_str  : str        ) -> EntityPath:
        """Persist a user-drawn path string into an ``EntityPath``
        row, creating one if absent or updating in place if
        present."""
        with transaction.atomic():
            try:
                entity_path = EntityPath.objects.get(
                    location = location,
                    entity_id = entity_id,
                )
                entity_path.svg_path = svg_path_str
                entity_path.save()
                return entity_path

            except EntityPath.DoesNotExist:
                pass

            entity = Entity.objects.get( id = entity_id )
            return EntityPath.objects.create(
                entity = entity,
                location = location,
                svg_path = svg_path_str,
            )

    def get_entity_position_form( self,
                                  entity         : Entity,
                                  location_view  : LocationView ) -> Optional[EntityPositionForm]:
        """Return an ``EntityPositionForm`` bound to the entity's
        existing position in this location, or None if the entity has
        no position row. Used by the entity edit-mode UI."""
        if not location_view:
            return None
        entity_position = EntityPosition.objects.filter(
            entity = entity,
            location = location_view.location,
        ).first()
        if not entity_position:
            return None
        return EntityPositionForm(
            location_view.location.svg_position_bounds,
            instance = entity_position,
        )

    def handle_entity_type_transition(
            self,
            entity         : Entity,
            location_view  : LocationView   = None ) -> Tuple[bool, EntityTransitionType]:
        """Transition an entity's persisted geometry between icon
        (EntityPosition) and path (EntityPath) representations
        following an entity_type change.

        Preservation strategy: when both representations already
        exist, leave both rows in place and just classify the
        transition for the caller. When only one exists and the new
        type needs the other, build the missing one from the
        existing one's center (path → icon uses path geometric
        center; icon → path uses position center) so the visual
        location is preserved across the type change. When neither
        exists, create a default-placement shape.

        Returns (transition_occurred, transition_type)."""
        if not location_view:
            return False, EntityTransitionType.NO_LOCATION_VIEW

        entity_type = entity.entity_type

        entity_position = EntityPosition.objects.filter(
            entity = entity,
            location = location_view.location,
        ).first()
        entity_path = EntityPath.objects.filter(
            entity = entity,
            location = location_view.location,
        ).first()

        has_position = bool( entity_position )
        has_path = bool( entity_path )
        needs_position = entity_type.requires_position()
        needs_path = entity_type.requires_path()

        had_both = has_position and has_path

        if had_both:
            with transaction.atomic():
                if needs_position:
                    return self._transition_path_to_icon(
                        entity = entity,
                        location_view = location_view,
                        entity_path = entity_path,
                    )
                else:
                    return self._transition_icon_to_path(
                        entity = entity,
                        location_view = location_view,
                        entity_position = entity_position,
                        is_path_closed = entity_type.requires_closed_path(),
                    )

        with transaction.atomic():
            if needs_position:
                if not has_position:
                    if has_path:
                        return self._transition_path_to_icon(
                            entity = entity,
                            location_view = location_view,
                            entity_path = entity_path,
                        )
                    self.ensure_default_shape_persisted(
                        entity = entity,
                        location_view = location_view,
                    )
                    return True, EntityTransitionType.CREATED_POSITION
                return True, EntityTransitionType.ICON_TO_ICON

            elif needs_path:
                if not has_path:
                    if has_position:
                        return self._transition_icon_to_path(
                            entity = entity,
                            location_view = location_view,
                            entity_position = entity_position,
                            is_path_closed = entity_type.requires_closed_path(),
                        )
                    self.ensure_default_shape_persisted(
                        entity = entity,
                        location_view = location_view,
                    )
                    return True, EntityTransitionType.CREATED_PATH
                return True, EntityTransitionType.PATH_TO_PATH

        return False, EntityTransitionType.NO_TRANSITION_NEEDED

    # ----- internal helpers -----

    def _derive_placement_shape( self,
                                 calculator       : EntityPlacementCalculator,
                                 entity           : Entity,
                                 bulk_grid_index  : Optional[int],
                                 bulk_grid_total  : Optional[int] ) -> PlacementShape:
        if (
            bulk_grid_total is not None
            and bulk_grid_total > 1
            and bulk_grid_index is not None
        ):
            return calculator._shape_at_grid_slot(
                entity = entity,
                grid_index = bulk_grid_index,
                grid_total = bulk_grid_total,
            )
        return calculator.shape_for_entity( entity = entity )

    def _create_entity_view( self,
                             entity           : Entity,
                             location_view    : LocationView,
                             placement_shape  : PlacementShape ) -> EntityView:
        with transaction.atomic():
            self._persist_placement_shape(
                entity = entity,
                location_view = location_view,
                placement_shape = placement_shape,
            )
            try:
                entity_view = EntityView.objects.get(
                    entity = entity,
                    location_view = location_view,
                )
            except EntityView.DoesNotExist:
                entity_view = EntityView.objects.create(
                    entity = entity,
                    location_view = location_view,
                )
        return entity_view

    def _delete_entity_view( self,
                             entity         : Entity,
                             location_view  : LocationView ):
        entity_view = EntityView.objects.get(
            entity = entity,
            location_view = location_view,
        )
        entity_view.delete()
        return

    def _persist_placement_shape( self,
                                  entity           : Entity,
                                  location_view    : LocationView,
                                  placement_shape  : PlacementShape ):
        if isinstance( placement_shape, PlacementPoint ):
            self._persist_position_if_needed(
                entity = entity,
                location_view = location_view,
                placement_point = placement_shape,
            )
        elif isinstance( placement_shape, PlacementPath ):
            self._persist_path_if_needed(
                entity = entity,
                location_view = location_view,
                placement_path = placement_shape,
            )
        else:
            raise TypeError(
                f'Unrecognized placement shape: {type(placement_shape).__name__}'
            )
        return

    def _persist_position_if_needed(
            self,
            entity           : Entity,
            location_view    : LocationView,
            placement_point  : PlacementPoint ) -> Optional[EntityPosition]:
        try:
            return EntityPosition.objects.get(
                location = location_view.location,
                entity = entity,
            )
        except EntityPosition.DoesNotExist:
            pass

        return EntityPosition.objects.create(
            entity = entity,
            location = location_view.location,
            svg_x = Decimal( str( placement_point.svg_x ) ),
            svg_y = Decimal( str( placement_point.svg_y ) ),
            svg_scale = placement_point.svg_scale,
            svg_rotate = Decimal( '0.0' ),
        )

    def _persist_path_if_needed(
            self,
            entity          : Entity,
            location_view   : LocationView,
            placement_path  : PlacementPath ) -> Optional[EntityPath]:
        try:
            return EntityPath.objects.get(
                location = location_view.location,
                entity = entity,
            )
        except EntityPath.DoesNotExist:
            pass

        return EntityPath.objects.create(
            entity = entity,
            location = location_view.location,
            svg_path = placement_path.svg_path,
        )

    def _transition_icon_to_path(
            self,
            entity           : Entity,
            location_view    : LocationView,
            entity_position  : EntityPosition,
            is_path_closed   : bool ) -> Tuple[bool, EntityTransitionType]:
        """Create an EntityPath centered on the existing position so
        the visual location is preserved. Existing EntityPath rows
        (if any) are preserved verbatim (preservation strategy
        allows easy reversion)."""
        center_x = float( entity_position.svg_x )
        center_y = float( entity_position.svg_y )

        svg_path = PathGeometry.create_default_path_string(
            view_box = location_view.svg_view_box,
            is_path_closed = is_path_closed,
            center_x = center_x,
            center_y = center_y,
            entity_type = entity.entity_type,
            radius_multiplier = 2.0,  # Larger for control-point visibility.
        )
        EntityPath.objects.get_or_create(
            entity = entity,
            location = location_view.location,
            defaults = { 'svg_path': svg_path },
        )
        return True, EntityTransitionType.ICON_TO_PATH

    def _transition_path_to_icon(
            self,
            entity         : Entity,
            location_view  : LocationView,
            entity_path    : EntityPath ) -> Tuple[bool, EntityTransitionType]:
        """Create an EntityPosition at the existing path's geometric
        center so the visual location is preserved. Falls back to
        the viewbox center when path-center extraction fails.
        Existing EntityPosition rows (if any) are preserved
        verbatim."""
        center_x, center_y = PositionGeometry.path_center( entity_path.svg_path )
        if center_x is None or center_y is None:
            center_x, center_y = PositionGeometry.view_center( location_view.svg_view_box )

        svg_scale = self._calculator_for( location_view ).default_icon_scale(
            entity = entity )
        EntityPosition.objects.get_or_create(
            entity = entity,
            location = location_view.location,
            defaults = {
                'svg_x': Decimal( str( center_x ) ),
                'svg_y': Decimal( str( center_y ) ),
                'svg_scale': svg_scale,
                'svg_rotate': Decimal( '0.0' ),
            },
        )
        return True, EntityTransitionType.PATH_TO_ICON