import json

import xbmc
import xbmcaddon
import xbmcgui
import xbmcvfs


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


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


def get_custom_groups():
    """Load custom channel groups from JSON file."""
    try:
        if xbmcvfs.exists(CUSTOM_GROUPS_PATH):
            with xbmcvfs.File(CUSTOM_GROUPS_PATH, "r") as f:
                return json.loads(f.read())
    except Exception:
        pass
    return []


def save_custom_groups(groups):
    """Save custom channel groups to JSON file."""
    try:
        with xbmcvfs.File(CUSTOM_GROUPS_PATH, "w") as f:
            f.write(json.dumps(groups, indent=2))
        return True
    except Exception as e:
        debug_log(f"Error saving custom groups: {e}", xbmc.LOGERROR)
        return False


def _load_available_channels_from_imported(dialog):
    profile_path = xbmcvfs.translatePath(xbmcaddon.Addon().getAddonInfo('profile'))
    imported_path = profile_path + "jet_guide_imported.json"
    if xbmcvfs.exists(imported_path):
        with xbmcvfs.File(imported_path, 'r') as f:
            available_channels = json.loads(f.read())
    else:
        available_channels = []
    if not available_channels:
        dialog.ok("No Channels", "No imported channels found. Import channels first.")
    return available_channels


def _load_available_channels_from_epg_cache(dialog):
    try:
        from cache import load_cache
        from jet_parser import get_active_guide, get_cache_files

        active_guide = get_active_guide()
        cache_files = get_cache_files(active_guide)
        m3u8_cache_file = cache_files['m3u8']
        m3u8_time_file = cache_files['m3u8_time']

        cached_data, _cache_time = load_cache(m3u8_cache_file, m3u8_time_file)
        if cached_data and isinstance(cached_data, list):
            return cached_data
        dialog.ok("No Channels", "No channel data found. Load the EPG first.")
        return []
    except Exception as e:
        debug_log(f"Error loading channel cache: {e}", xbmc.LOGERROR)
        dialog.ok("Error", "Failed to load channel list. Make sure EPG has been opened at least once.")
        return []


def create_custom_group():
    """Create a new custom channel group."""
    dialog = xbmcgui.Dialog()

    group_name = dialog.input("Enter group name", defaultt="My Custom Group")
    if not group_name:
        return

    choice = dialog.select("Add channels from", ["Favorites (jet_guide_imported)", "Browse all channels"])
    if choice == -1:
        return

    if choice == 0:
        available_channels = _load_available_channels_from_imported(dialog)
    else:
        available_channels = _load_available_channels_from_epg_cache(dialog)

    if not available_channels:
        return

    channel_titles = [c.get('name', c.get('title', 'Unknown')) for c in available_channels]
    selected = dialog.multiselect(f"Select channels for '{group_name}'", channel_titles)

    if selected is None or len(selected) == 0:
        return

    selected_channels = [available_channels[i] for i in selected]
    groups = get_custom_groups()

    if any(g.get('name') == group_name for g in groups):
        dialog.ok("Error", "A group with this name already exists.")
        return

    groups.append({"name": group_name, "channels": selected_channels})

    if save_custom_groups(groups):
        dialog.notification(
            "Success",
            f"Group '{group_name}' created with {len(selected_channels)} channels",
            xbmcgui.NOTIFICATION_INFO,
            3000,
        )
    else:
        dialog.ok("Error", "Failed to save group.")


def manage_custom_groups():
    """Manage custom channel groups - edit, delete."""
    dialog = xbmcgui.Dialog()
    groups = get_custom_groups()

    if not groups:
        if dialog.yesno("No Custom Groups", "No custom groups found. Would you like to create one?"):
            create_custom_group()
        return

    while True:
        group_names = [g.get('name', 'Unnamed') + f" ({len(g.get('channels', []))} channels)" for g in groups]
        choice = dialog.select("Manage Custom Groups", group_names + ["[Create New Group]", "[Done]"])

        if choice == -1 or choice == len(group_names) + 1:
            break

        if choice == len(group_names):
            create_custom_group()
            groups = get_custom_groups()
            continue

        selected_group = groups[choice]
        channel_count = len(selected_group.get('channels', []))
        sub_choice = dialog.select(
            f"{selected_group.get('name')}",
            [
                f"View Channels ({channel_count})",
                "Add Channels",
                "Remove Channels",
                "Rename Group",
                "Delete Group",
                "Cancel",
            ],
        )

        if sub_choice == 0:
            channels = selected_group.get('channels', [])
            if channels:
                channel_list = "\n".join([c.get('title', c.get('name', 'Unknown')) for c in channels])
                dialog.textviewer("Channels in Group", channel_list)
            else:
                dialog.ok("Empty Group", "This group has no channels.")
        elif sub_choice == 1:
            source_choice = dialog.select("Add channels from", ["Favorites (jet_guide_imported)", "Browse all channels (EPG)"])
            if source_choice == -1:
                continue

            if source_choice == 0:
                available_channels = _load_available_channels_from_imported(dialog)
                if not available_channels:
                    dialog.ok("No Channels", "No imported channels available.")
                    continue
            else:
                available_channels = _load_available_channels_from_epg_cache(dialog)
                if not available_channels:
                    continue

            current_links = {c.get('link', c.get('url', '')) for c in selected_group.get('channels', [])}
            available_channels = [c for c in available_channels if c.get('link', c.get('url', '')) not in current_links]

            if not available_channels:
                dialog.ok("All Added", "All imported channels are already in this group.")
                continue

            channel_titles = [c.get('name', c.get('title', 'Unknown')) for c in available_channels]
            selected = dialog.multiselect("Select channels to add", channel_titles)

            if selected is not None and len(selected) > 0:
                new_channels = [available_channels[i] for i in selected]
                selected_group['channels'].extend(new_channels)
                if save_custom_groups(groups):
                    dialog.notification("Success", f"Added {len(new_channels)} channels", xbmcgui.NOTIFICATION_INFO, 2000)
                groups = get_custom_groups()
        elif sub_choice == 2:
            channels = selected_group.get('channels', [])
            if not channels:
                dialog.ok("Empty Group", "No channels to remove.")
                continue

            channel_titles = [c.get('title', c.get('name', 'Unknown')) for c in channels]
            selected = dialog.multiselect("Select channels to remove", channel_titles)

            if selected is not None and len(selected) > 0:
                for i in sorted(selected, reverse=True):
                    channels.pop(i)
                selected_group['channels'] = channels
                if save_custom_groups(groups):
                    dialog.notification("Success", f"Removed {len(selected)} channels", xbmcgui.NOTIFICATION_INFO, 2000)
                groups = get_custom_groups()
        elif sub_choice == 3:
            new_name = dialog.input("Enter new name", defaultt=selected_group.get('name', ''))
            if new_name:
                selected_group['name'] = new_name
                if save_custom_groups(groups):
                    dialog.notification("Success", "Group renamed", xbmcgui.NOTIFICATION_INFO, 2000)
                groups = get_custom_groups()
        elif sub_choice == 4:
            if dialog.yesno("Delete Group", f"Are you sure you want to delete '{selected_group.get('name')}'?"):
                groups.pop(choice)
                if save_custom_groups(groups):
                    dialog.notification("Deleted", "Group removed", xbmcgui.NOTIFICATION_INFO, 2000)
                groups = get_custom_groups()
