"""Channel-aware collection path placement (Magento hierarchy vs Shopify flat)."""

from __future__ import annotations

from typing import Any, Dict, List, Optional

from channel.url_canonical import build_plp_url, normalize_plp_path, slugify_segment


def default_parent_path_slug(category_l1: Optional[str]) -> Optional[str]:
    """Current default: collection is a direct child of the top hub category."""
    hub = normalize_plp_path(category_l1 or "")
    return hub or None


def effective_parent_path_slug(
    *,
    category_l1: Optional[str],
    parent_path_slug: Optional[str] = None,
) -> Optional[str]:
    explicit = normalize_plp_path(parent_path_slug) if parent_path_slug else None
    if explicit:
        return explicit
    return default_parent_path_slug(category_l1)


def shopify_collection_title(collection: Optional[str], path_slug: Optional[str] = None) -> str:
    coll = _strip_hub_prefix(str(collection or "").strip())
    if coll:
        return coll
    slug = normalize_plp_path(path_slug or "")
    if not slug:
        return ""
    return slug.split("/")[-1].replace("-", " ").title()


def shopify_collection_handle(collection: Optional[str], path_slug: Optional[str] = None) -> str:
    title = shopify_collection_title(collection, path_slug)
    return slugify_segment(title) if title else slugify_segment(path_slug or "collection")


def magento_breadcrumb(
    *,
    category_l1: str,
    collection: str,
    parent_path_slug: Optional[str],
) -> List[str]:
    parent = effective_parent_path_slug(category_l1=category_l1, parent_path_slug=parent_path_slug)
    hub = normalize_plp_path(category_l1)
    collection = _strip_hub_prefix(collection, category_l1=category_l1)
    crumbs = [category_l1]
    if parent and parent != hub:
        crumbs.append(_title_from_slug_segment(parent.split("/")[-1]))
    crumbs.append(collection)
    return crumbs


def build_channel_placement(
    *,
    channel_code: str,
    path_slug: str,
    category_l1: str,
    collection: str,
    parent_path_slug: Optional[str] = None,
) -> Dict[str, Any]:
    """Describe how a master collection path maps onto a downstream channel."""
    channel = str(channel_code or "").strip().lower()
    slug = normalize_plp_path(path_slug)
    parent = effective_parent_path_slug(category_l1=category_l1, parent_path_slug=parent_path_slug)
    hub = normalize_plp_path(category_l1)

    if channel == "shopify":
        title = shopify_collection_title(collection, slug)
        return {
            "channel_code": "shopify",
            "structure": "flat",
            "supports_hierarchy": False,
            "remote_taxonomy_kind": "collection",
            "remote_title": title,
            "remote_handle": shopify_collection_handle(collection, slug),
            "master_path_slug": slug,
            "master_parent_path_slug": None,
            "hub_path_slug": hub or None,
            "breadcrumb": [title],
            "notes": "Shopify has no category tree; one manual collection per master collection title.",
        }

    return {
        "channel_code": "magento",
        "structure": "hierarchical",
        "supports_hierarchy": True,
        "remote_taxonomy_kind": "category",
        "master_path_slug": slug,
        "master_parent_path_slug": parent,
        "hub_path_slug": hub or None,
        "breadcrumb": magento_breadcrumb(
            category_l1=category_l1,
            collection=collection,
            parent_path_slug=parent_path_slug,
        ),
        "url_path": build_plp_url(slug),
        "notes": (
            "Collection is a Magento category child. Default parent is the top hub; "
            "set parent_path_slug to nest under a subcategory later."
        ),
    }


def _title_from_slug_segment(segment: str) -> str:
    return str(segment or "").replace("-", " ").strip().title()


def _strip_hub_prefix(value: str, *, category_l1: Optional[str] = None) -> str:
    text = str(value or "").strip()
    if not text:
        return ""
    hub = str(category_l1 or "").strip()
    candidates = [hub] if hub else []
    candidates.extend(["Kitchen Cabinets"])
    for candidate in candidates:
        if not candidate:
            continue
        for separator in (" / ", "/", " - ", " > "):
            prefix = f"{candidate}{separator}"
            if text.lower().startswith(prefix.lower()):
                return text[len(prefix):].strip()
    return text
