import json
import re
from .constants import LANG_DIR, LANG_DISP, HOLIDAY_NAME_KEY

_ICON_PATTERN = re.compile(r"^[\s🏠📅📝✅📄▣▦⌂✎✓•·]+")


def load_lang(code: str) -> dict:
    try:
        with open(LANG_DIR / f"{code}.json", "r", encoding="utf-8") as f:
            return json.load(f)
    except Exception:
        with open(LANG_DIR / "zh_CN.json", "r", encoding="utf-8") as f:
            return json.load(f)


def load_all_langs() -> dict:
    return {code: load_lang(code) for code in LANG_DISP.keys()}


def clean_label(text) -> str:
    return _ICON_PATTERN.sub("", str(text or "")).strip()


def all_lang_values(all_langs: dict, key: str) -> set:
    values = set()
    for lang in all_langs.values():
        value = str(lang.get(key, "")).strip()
        if value:
            values.add(value)
    return values


def is_placeholder_value(all_langs: dict, key: str, value: str) -> bool:
    return str(value or "").strip() in all_lang_values(all_langs, key)


def holiday_text(obj, lang_code: str) -> str:
    if isinstance(obj, dict):
        key = HOLIDAY_NAME_KEY.get(lang_code, "zh")
        return obj.get(key) or obj.get("zh") or obj.get("en") or obj.get("id") or ""
    return str(obj or "")
