import json

import xbmc
import xbmcaddon
import xbmcgui
import xbmcvfs

from tools_custom_groups import manage_custom_groups


def debug_log(msg, level=xbmc.LOGINFO):
    xbmc.log(f"[jet_guide] {msg}", level)


ADDON = xbmcaddon.Addon()

EPG_CATEGORIES_ENABLED_PATH = xbmcvfs.translatePath(
    "special://userdata/addon_data/plugin.video.jet_guide/epg_categories_enabled.json"
)

EPG_CATEGORY_SETTING_MAP = {
    "epg_cat_us_local": "US LOCAL",
    "epg_cat_us_entertainment": "US Entertainment",
    "epg_cat_us_movies": "US Movies",
    "epg_cat_us_music": "US Music",
    "epg_cat_uk_entertainment": "UK Entertainment",
    "epg_cat_uk_movies": "UK Movies",
    "epg_cat_uk_music": "UK Music",
    "epg_cat_sports_networks": "Sports Networks",
    "epg_cat_sports_other": "Sports Networks  Other",
    "epg_cat_sports_bein": "Sports Networks  beIN",
    "epg_cat_sports_regional": "Sports Networks Regional",
    "epg_cat_sports_fanduel": "Sports Fan Duel",
    "epg_cat_sports_aus_fox": "Sports Aus Fox",
    "epg_cat_sports_dazn": "Sports DAZN",
    "epg_cat_news": "News",
    "epg_cat_international": "International",
    "epg_cat_league_pass": "League Pass",
    "epg_cat_all": "All",
}


def get_epg_categories_enabled():
    """Load enabled EPG categories from settings and JSON file."""
    try:
        categories = {}
        if xbmcvfs.exists(EPG_CATEGORIES_ENABLED_PATH):
            with xbmcvfs.File(EPG_CATEGORIES_ENABLED_PATH, "r") as f:
                categories = json.loads(f.read())

        for setting_id, category_name in EPG_CATEGORY_SETTING_MAP.items():
            try:
                categories[category_name] = ADDON.getSettingBool(setting_id)
            except Exception:
                pass
        return categories
    except Exception:
        pass
    return {}


def save_epg_categories_enabled(categories):
    """Save enabled EPG categories to settings and JSON file."""
    try:
        for setting_id, category_name in EPG_CATEGORY_SETTING_MAP.items():
            enabled = categories.get(category_name, True)
            ADDON.setSettingBool(setting_id, enabled)

        with xbmcvfs.File(EPG_CATEGORIES_ENABLED_PATH, "w") as f:
            f.write(json.dumps(categories, indent=2))
        return True
    except Exception as e:
        debug_log(f"Error saving EPG categories: {e}", xbmc.LOGERROR)
        return False


def manage_epg_categories():
    """Manage which EPG categories are shown in the category filter."""
    dialog = xbmcgui.Dialog()
    enabled_categories = get_epg_categories_enabled()

    all_possible_categories = [
        "US LOCAL",
        "US Entertainment",
        "US Movies",
        "US Music",
        "UK Entertainment",
        "UK Movies",
        "UK Music",
        "Sports Networks",
        "Sports Networks  Other",
        "Sports Networks  beIN",
        "Sports Networks Regional",
        "Sports Fan Duel",
        "Sports Aus Fox",
        "Sports DAZN",
        "News",
        "International",
        "League Pass",
        "All"
    ]

    while True:
        options = []
        for cat in all_possible_categories:
            is_enabled = enabled_categories.get(cat, True)
            if is_enabled:
                options.append(f"[COLOR lime] {cat}[/COLOR]")
            else:
                options.append(f"[COLOR red][OFF][/COLOR] {cat}")

        options.append("")
        options.append("Manage Custom Groups...")
        options.append("Done")

        choice = dialog.select("EPG Categories - ✓ = Shown, [OFF] = Hidden", options)

        if choice == -1 or choice >= len(options) - 2:
            break

        if choice < len(all_possible_categories):
            category = all_possible_categories[choice]
            current_state = enabled_categories.get(category, True)
            enabled_categories[category] = not current_state
            save_epg_categories_enabled(enabled_categories)
        elif choice == len(options) - 2:
            manage_custom_groups()
