import xbmcgui
import xbmcaddon
import xbmc
import threading

from ai_assistant import (
    is_enabled, ask, analyze_game, search_channels,
    get_game_info, quick_ask
)
from ai_cache import get_usage
from tools import debug_log

addon = xbmcaddon.Addon()


def _get_daily_limit():
    try:
        return int(addon.getSetting('ai_daily_limit') or '100')
    except ValueError:
        return 100


def show_ai_dialog():
    if not is_enabled():
        xbmcgui.Dialog().ok(
            "AI Assistant",
            "AI Assistant is not enabled.\n\n"
            "Get a free API key at:\nhttps://aistudio.google.com/apikey\n\n"
            "Then enter it in Settings > AI Assistant"
        )
        return

    usage = get_usage()
    daily_count = usage.get('count', 0)
    daily_limit = _get_daily_limit()

    query = xbmcgui.Dialog().input('Ask Jet Guide AI anything...', type=xbmcgui.INPUT_ALPHANUM)
    if not query:
        return

    show_loading()
    response, error = ask(query)
    hide_loading()

    if error:
        xbmcgui.Dialog().ok("AI Error", str(error))
    elif response:
        show_response(response, daily_count + 1, daily_limit)


def show_ai_with_context(game_data):
    if not is_enabled():
        xbmcgui.Dialog().ok(
            "AI Assistant",
            "AI Assistant is not enabled.\n\n"
            "Get a free API key at:\nhttps://aistudio.google.com/apikey"
        )
        return

    options = ["Analyze Game", "Ask About Game", "Cancel"]
    idx = xbmcgui.Dialog().select("AI Assistant", options)
    if idx == -1 or idx == 2:
        return

    show_loading()
    if idx == 0:
        response, error = analyze_game(game_data)
    else:
        response, error = get_game_info(game_data)

    hide_loading()

    if error:
        xbmcgui.Dialog().ok("AI Error", str(error))
    elif response:
        show_response(response)


def show_ai_search(channels):
    if not is_enabled():
        xbmcgui.Dialog().ok(
            "AI Assistant",
            "AI not enabled. Set API key in Settings."
        )
        return

    query = xbmcgui.Dialog().input('Describe what you want to watch...', type=xbmcgui.INPUT_ALPHANUM)
    if not query:
        return

    show_loading()
    response, error = search_channels(query, channels)
    hide_loading()

    if error:
        xbmcgui.Dialog().ok("AI Error", str(error))
    elif response:
        show_response(response)


def show_response(response, usage=None, limit=None):
    lines = response.split('\n')
    display_lines = []
    for line in lines[:30]:
        if line.strip():
            display_lines.append(line)

    if usage is not None and limit is not None:
        display_lines.append(f"\n--- Daily requests: {usage}/{limit} ---")

    dialog = xbmcgui.Dialog()
    dialog.textviewer("AI Response", '\n'.join(display_lines))


def show_loading():
    xbmc.executebuiltin('ActivateWindow(busydialog)')


def hide_loading():
    xbmc.executebuiltin('Dialog.Close(busydialog)')


def get_ai_menu_items():
    if not is_enabled():
        return []
    return [
        {
            'label': 'AI Assistant',
            'action': 'ai_assistant'
        },
        {
            'label': 'AI Search',
            'action': 'ai_search'
        }
    ]


def handle_ai_action(action, context=None):
    if action == 'ai_assistant':
        if context:
            show_ai_with_context(context)
        else:
            show_ai_dialog()
    elif action == 'ai_search':
        if context and isinstance(context, list):
            show_ai_search(context)
        else:
            show_ai_dialog()
