"""Runtime lookup: YAML first, hardcoded module fallback.

Callers ask for selectors by (site_id, column_id). The registry checks
`config/sites/<site_id>.yaml` first; if absent, falls back to the hardcoded
Python module (currently only `sites/gdqy.py`). Phase 2 flips fully to YAML
once multi-site loading is in place.
"""
from __future__ import annotations

from functools import lru_cache
from pathlib import Path

from govcrawler.config.loader import SiteConfig, load_sites_dir

DEFAULT_CONFIG_DIR = Path(__file__).resolve().parents[2] / "config" / "sites"


@lru_cache(maxsize=1)
def _registry() -> dict[str, SiteConfig]:
    return load_sites_dir(DEFAULT_CONFIG_DIR)


def reload() -> None:
    """Bust the lru_cache — tests and hot-reload path."""
    _registry.cache_clear()


def get_site_config(site_id: str) -> SiteConfig | None:
    return _registry().get(site_id)


def get_detail_selectors(site_id: str, column_id: str) -> dict | None:
    """Return a plain dict shaped like sites/gdqy.py DETAIL_SELECTORS, or None.

    Preferring YAML; falling back to the hardcoded gdqy module keeps Plan 01-03
    smoke path working during the Phase 2 migration.
    """
    site = get_site_config(site_id)
    if site is not None:
        col = site.get_column(column_id)
        if col is not None:
            return {
                "title": col.detail.title,
                "publish_time": col.detail.publish_time,
                "source": col.detail.source,
                "content": col.detail.content,
                "attachment_css": col.detail.attachment_css,
            }
    # Legacy fallback: hardcoded module for gdqy during migration
    if site_id == "gdqy":
        from govcrawler.sites.gdqy import DETAIL_SELECTORS
        return DETAIL_SELECTORS
    return None
