import logging
import os
import json
import time
import copy

logger = logging.getLogger(__name__)

# Cache for selector config with hot-reload support
_config_cache: dict = {}
_config_mtime: float = 0.0

_SEARCH_URL_ENV_OVERRIDES = {
    "searxng": ("SEARXNG_SEARCH_URL", "JUSTSEARCH_SEARXNG_SEARCH_URL"),
}


def _apply_env_overrides(config: dict) -> dict:
    """Return selector config with deployment-specific search URLs applied."""
    result = copy.deepcopy(config)
    for engine, env_names in _SEARCH_URL_ENV_OVERRIDES.items():
        engine_config = result.get(engine)
        if not isinstance(engine_config, dict):
            continue
        for env_name in env_names:
            override = os.getenv(env_name, "").strip()
            if override:
                engine_config["base_url"] = override
                break
    return result


def load_selectors(engine: str = "searxng") -> dict:
    """Load search engine CSS selectors from config file.
    
    Supports hot-reload: if the config file has been modified since last load,
    it will be re-read automatically.
    
    Returns the full engine config dict. Callers extract the specific engine by name.
    """
    global _config_cache, _config_mtime

    config_path = os.path.join(os.path.dirname(__file__), 'search_selectors.json')
    
    try:
        # Check for file modification (hot-reload)
        current_mtime = os.path.getmtime(config_path)
        if current_mtime != _config_mtime:
            with open(config_path, 'r', encoding='utf-8') as f:
                _config_cache = json.load(f)
                _config_mtime = current_mtime
                logger.info("[SearchEngine] 重新加载搜索引擎配置 (mtime=%.0f)", _config_mtime)
    except OSError as e:
        logger.error("[SearchEngine] 加载搜索引擎配置失败: %s", e)
    
    config = _apply_env_overrides(_config_cache)
    if not config:
        # Fallback default
        config = {
            "searxng": {
                "base_url": "https://searx.be/search?q={query}&format=html",
                "selectors": {
                    "result_container": ["article.result", ".result"],
                    "title": "h3 a",
                    "link": "h3 a",
                    "snippet": ".content, p",
                    "date": ""
                },
                "captcha_check": [],
                "wait_selector": "#results, .result"
            }
        }

    if engine is None:
        return config

    if engine in config:
        return config[engine]
    # Engine not in config — return the stable default engine.
    return config.get("searxng", {})


def get_all_engines() -> list:
    """Return a list of all available search engine names."""
    global _config_cache
    if not _config_cache:
        load_selectors()  # Force load
    return list(_config_cache.keys()) if _config_cache else ["searxng"]
