"""Section handler registry.

Each shop section (hulls, bpc, ...) registers a SectionHandler that carries the
section-specific stockroom behavior. The generic stockroom views stay section-agnostic
and delegate to the handler for the source's section.
"""

from ..forms import AddStockroomForm


class SectionHandler:
    section = None  # section key, e.g. "hulls"
    stockroom_form_class = AddStockroomForm  # form used to add a stockroom
    edit_stockroom_form_class = None  # form used to edit one (None = not editable)
    manage_template = (
        "shop/manage_section_stub.html"  # back-office page for this section
    )
    featured_model = (
        None  # listing model whose rows can be starred (None = no featuring)
    )

    # --- page rendering (generic views delegate here; no per-section branches) ---

    def manage_context(self, shop, request):
        """Extra template context for this section's back-office page. Default: none."""
        return {}

    def storefront_context(self, shop, request):
        """Extra template context for this section's public page. Default: none."""
        return {}

    def build_order_line(self, shop, listing_id):
        """Snapshot dict {section, eve_type, unit_price, listing_id} for a valid,
        orderable listing in this shop, or None if it isn't orderable here.
        Default: this section is not orderable."""
        return None

    def stockroom_added(self, source, cleaned_data):
        """Configure the new source + auto-list + recompute (section-specific)."""

    def stockroom_edited(self, source, cleaned_data):
        """Apply an edit to an existing source (section-specific)."""

    def stockroom_removed(self, shop):
        """React to a source removal (e.g. recompute stock)."""

    # --- periodic refresh (the single refresh_all_stock beat drives these) ---

    def shops_to_recompute(self):
        """Shop pks whose stored stock for this section should be recomputed.

        Return an iterable of pks. Default: nothing (a section with no stored stock).
        """
        return []

    def enqueue_source_refresh(self):
        """Enqueue upstream data pulls this section's stock derives from (corptools
        assets, ESI blueprints, ...). Async; the recompute reflects it within a cycle.
        Default: nothing to refresh. Return the affected ids (for logging/tests).
        """
        return []

    def recompute(self, shop):
        """Recompute this section's stored stock for one shop. Default: no-op."""


_REGISTRY = {}


def register(handler):
    _REGISTRY[handler.section] = handler
    return handler


def handler_for(section):
    return _REGISTRY.get(section)


def handlers():
    """All registered section handlers (registration order)."""
    return list(_REGISTRY.values())
