"""Export collection landing pages for channel presentation push."""

from __future__ import annotations

from typing import Any, Dict, List, Optional

from sqlalchemy import select
from sqlalchemy.orm import Session

from channel.url_canonical import normalize_plp_path
from db.channel_taxonomy import list_taxonomy_mappings
from db.collection_channel_placement import build_channel_placement
from db.collection_landing_pages import list_collection_landing_pages
from db.collection_sku_mapping import resolve_collection_skus
from db.models import CollectionLandingPage


def export_collections_for_channel(
    session: Session,
    *,
    channel_code: str,
    category_l1: Optional[str] = None,
    connection_id: Optional[int] = None,
    include_inferred: bool = True,
    include_skus: bool = True,
    limit: int = 500,
) -> Dict[str, Any]:
    """Channel-ready DTO: landing metadata + resolved SKUs + taxonomy ids."""
    rows = list_collection_landing_pages(
        session,
        category_l1=category_l1,
        include_inferred=include_inferred,
        limit=limit,
    )
    saved_slugs = {
        normalize_plp_path(path)
        for path in session.scalars(select(CollectionLandingPage.path_slug)).all()
        if str(path or "").strip()
    }
    taxonomy = {
        row["master_path_key"]: row
        for row in list_taxonomy_mappings(
            session,
            channel_code=channel_code,
            connection_id=connection_id,
        )
    }

    collections: List[Dict[str, Any]] = []
    from db.collection_path_guard import is_polluted_hub_collection_path

    for row in rows:
        if not row.get("is_active", True):
            continue
        slug = normalize_plp_path(row.get("path_slug") or "")
        if not slug:
            continue
        if is_polluted_hub_collection_path(session, slug):
            continue
        item = dict(row)
        item["has_landing_content"] = slug in saved_slugs and not row.get("inferred")
        taxonomy_row = taxonomy.get(slug) or taxonomy.get(row.get("collection") or "")
        item["channel"] = {
            "channel_code": channel_code,
            "connection_id": connection_id,
            "taxonomy": taxonomy_row,
            "placement": build_channel_placement(
                channel_code=channel_code,
                path_slug=slug,
                category_l1=str(row.get("category_l1") or "Kitchen Cabinets"),
                collection=str(row.get("collection") or row.get("title") or ""),
                parent_path_slug=row.get("parent_path_slug"),
            ),
        }
        if include_skus:
            resolved = resolve_collection_skus(
                session,
                path_slug=slug,
                category_l1=row.get("category_l1"),
                collection=row.get("collection"),
                sku_prefixes=row.get("sku_prefixes"),
            )
            item["skus"] = resolved.get("skus") or []
            item["sku_count"] = resolved.get("sku_count") or 0
            item["sku_prefixes"] = resolved.get("sku_prefixes") or []
        collections.append(item)

    return {
        "channel_code": channel_code,
        "connection_id": connection_id,
        "category_l1": category_l1,
        "count": len(collections),
        "collections": collections,
    }
