"""Cleanup polluted collection filter profiles already written to registry aliases."""

from __future__ import annotations

from datetime import datetime, timezone
from typing import Any, Dict, List, Optional

from sqlalchemy import select
from sqlalchemy.orm import Session

from db.collection_path_guard import is_polluted_collection_name
from db.collection_landing_pages import canonical_collection, canonical_category
from db.models import MasterCollectionRegistry


def cleanup_polluted_collection_filter_profiles(
    session: Session,
    *,
    category_l1: Optional[str] = "Kitchen Cabinets",
    dry_run: bool = True,
) -> Dict[str, Any]:
    category = canonical_category(category_l1) or category_l1 or "Kitchen Cabinets"
    rows = list(
        session.scalars(
            select(MasterCollectionRegistry)
            .where(MasterCollectionRegistry.is_active.is_(True))
            .order_by(MasterCollectionRegistry.name)
        ).all()
    )
    candidates: List[Dict[str, Any]] = []
    updated = 0
    for row in rows:
        aliases = dict(row.aliases or {})
        has_filter_state = any(
            key in aliases
            for key in (
                "filter_attributes",
                "filter_attribute_sources",
                "brochure_filter_attributes",
                "brochure_filter_attribute_sources",
            )
        )
        if not has_filter_state:
            continue
        name = canonical_collection(row.name) or str(row.name or "").strip()
        if not name:
            continue
        if not is_polluted_collection_name(session, name, category_l1=category):
            continue
        item = {
            "registry_id": row.id,
            "collection": name,
            "path_slug": row.path_slug,
            "had_keys": sorted(
                key
                for key in (
                    "filter_attributes",
                    "filter_attribute_sources",
                    "brochure_filter_attributes",
                    "brochure_filter_attribute_sources",
                )
                if key in aliases
            ),
        }
        candidates.append(item)
        if dry_run:
            continue
        for key in (
            "filter_attributes",
            "filter_attribute_sources",
            "brochure_filter_attributes",
            "brochure_filter_attribute_sources",
        ):
            aliases.pop(key, None)
        note = str(aliases.get("pollution_cleanup_note") or "").strip()
        stamp = f"polluted filter profile removed {datetime.now(timezone.utc).isoformat()}"
        aliases["pollution_cleanup_note"] = f"{note} | {stamp}".strip(" |")
        row.aliases = aliases
        updated += 1

    return {
        "status": "ok",
        "dry_run": dry_run,
        "category_l1": category,
        "candidate_count": len(candidates),
        "would_update": len(candidates) if dry_run else 0,
        "updated": updated if not dry_run else 0,
        "candidates": candidates[:200],
    }
