from __future__ import annotations

import json
from functools import lru_cache
from pathlib import Path


MAPPING_PATH = Path(__file__).resolve().parents[1] / "resources" / "menu_path_mapping.json"


@lru_cache(maxsize=1)
def menu_path_mapping() -> dict:
    if not MAPPING_PATH.exists():
        return {"paths": {}}
    return json.loads(MAPPING_PATH.read_text(encoding="utf-8"))


def is_production_url(url: str) -> bool:
    return "shunfju.com" in (url or "")


def menu_entries_for_path(
    path: str,
    *,
    app_hint: str = "",
    component: str = "",
) -> list[dict[str, str]]:
    entries = list(menu_path_mapping().get("paths", {}).get(path, []))
    if component:
        component_matches = [entry for entry in entries if entry.get("component") == component]
        if component_matches:
            entries = component_matches
    if app_hint:
        app_matches = [
            entry
            for entry in entries
            if app_hint in {entry.get("test_app", ""), entry.get("production_app", "")}
        ]
        if app_matches:
            entries = app_matches
    return entries


def menu_names_for_path(
    path: str,
    *,
    production: bool,
    app_hint: str = "",
    component: str = "",
) -> list[str]:
    key = "production_menu" if production else "test_menu"
    names: list[str] = []
    for entry in menu_entries_for_path(path, app_hint=app_hint, component=component):
        name = str(entry.get(key) or "").strip()
        if name and name not in names:
            names.append(name)
    return names
