from multiplayer_crosswords.dictionary import Dictionary, Word
import json
from pathlib import Path

def load_dictionary(p: str | Path) -> Dictionary:
    if not hasattr(load_dictionary, "_cache"):
        load_dictionary._cache = {}
    cache_key = str(p)
    if cache_key in load_dictionary._cache:
        return load_dictionary._cache[cache_key]
    p = Path(p)
    if not p.exists():
        raise FileNotFoundError(f"Dictionary file not found: {p}")
    with p.open("r", encoding="utf-8") as f:
        data = json.load(f)
    
    dict_obj = Dictionary()

    for key, obj in data.items():
        word = obj.get("word", "").strip()
        if not word.isalpha():
            continue
        word = word.lower()

        hints = []
        try:
            if "senses" in obj:
                for sense in obj["senses"]:
                    text = sense
                    if word in text.lower():
                        continue
                    hints.append(text)
        except Exception:
            pass

        try:
            if "synonyms" in obj:
                for synonym in obj["synonyms"]:
                    text = synonym
                    if word in text.lower():
                        continue
                    hints.append( text)
        except Exception:
            pass
            
        try:
            if "antonyms" in obj:
                for antonym in obj["antonyms"]:
                    text = antonym
                    if word in text.lower():
                        continue
                    if "de" in p.name:
                        text = "Gegenteil von " + text
                    else:
                        text = "Opposite of " + text
                    hints.append( text)
        except Exception:
            pass

        if len(hints) > 0:

            difficulty = 1.0
            word_freq = obj.get("word_frequency", -1)
            if word_freq >= 0:
                 # Map 0-100 frequency to 1.0-0.0 difficulty
                 # Higher frequency -> Lower difficulty
                 difficulty = max(0.0, min(1.0, 1.0 - (word_freq / 100.0)))

            w = Word(word=word,
                    hints=hints,
                    difficulty=difficulty)
            dict_obj.add_word(w)
    load_dictionary._cache[cache_key] = dict_obj
    return dict_obj

def load_en_dictionary() -> Dictionary:
    return load_dictionary(Path(__file__).parent.parent / "data" / "en.json")

def load_de_dictionary() -> Dictionary:
    return load_dictionary(Path(__file__).parent.parent / "data" / "de.json")
