import os
import re
import subprocess
import sys
import time
import urllib.parse

import xbmc
import xbmcaddon
import xbmcgui

xbc = xbmc
xbcaddon = xbmcaddon
xbcgui = xbmcgui


def _show_directions_199():
    readme_path = os.path.join(os.path.dirname(__file__), "README_tenbuttons_199.md")
    if os.path.exists(readme_path):
        with open(readme_path, "r", encoding="utf-8") as f:
            directions = f.read()
        xbmcgui.Dialog().textviewer("Directions", directions)
    else:
        xbmcgui.Dialog().ok("Directions", "Directions file not found.")
    return



def _handle_choice_play_mpv(url, mpv_path, get_resolved_url):
    resolved_url, resolved_headers = get_resolved_url(url)
    if not resolved_url or not resolved_url.startswith("http"):
        xbc.log(f"DEBUG: Invalid or unresolved stream URL: {resolved_url}", level=xbc.LOGERROR)
        xbcgui.Dialog().ok("Error", "Unable to resolve a valid stream URL. Try playing the stream in Kodi first or use a direct URL.")
        return

    proxy_match = re.match(r"http://127\.0\.0\.1:\d+\?url=(http.*)", resolved_url)
    if proxy_match:
        resolved_url = urllib.parse.unquote(proxy_match.group(1))
        xbc.log(f"DEBUG: Decoded proxy URL for mpv: {resolved_url}", level=xbc.LOGINFO)

    if xbc.getCondVisibility('system.platform.android'):
        package = 'is.xyz.mpv'
        intent = 'android.intent.action.VIEW'
        android_url = resolved_url
        if resolved_headers:
            # Use Kodi-style headers (not percent-encoded) for Android mpv
            header_params = "&".join([f"{k}={v}" for k, v in resolved_headers.items() if k.lower() in ["user-agent", "referer", "origin"]])
            if header_params:
                # FIXED: Actually append headers to URL instead of overwriting
                android_url = f"{resolved_url}|{header_params}"
                xbc.log(f"DEBUG: Android URL with headers: {android_url}", level=xbc.LOGINFO)

        # Try launching mpv via intent with explicit activity
        try:
            # Use raw android_url, do not quote
            try:
                xbc.executebuiltin(f'StartAndroidActivity("{package}","{intent}","video/*","{android_url}")')
                xbc.log(f"DEBUG: Attempted to launch mpv with intent URL: {android_url}", level=xbc.LOGINFO)
            except Exception as e:
                xbc.log(f"DEBUG: Failed to launch mpv intent: {str(e)}", level=xbc.LOGERROR)
                xbcgui.Dialog().ok("Error", f"Failed to launch mpv app: {str(e)}")
            xbcgui.Dialog().notification("mpv", "Stream sent to mpv app", xbcgui.NOTIFICATION_INFO, 2000)
        except Exception as e:
            xbc.log(f"DEBUG: Failed to launch mpv intent: {str(e)}", level=xbc.LOGERROR)
            xbcgui.Dialog().ok("Error", f"Failed to launch mpv: {str(e)}\nManually enter this URL in mpv:\n{android_url}")
        return
    else:
        # Non-Android handling
        mpv_args = []
        if resolved_headers:
            mpv_headers = ",".join([f"{k.title().replace('-', '-')}: {v}" for k, v in resolved_headers.items()])
            mpv_args += [f'--http-header-fields={mpv_headers}']
        mpv_command = [mpv_path] + mpv_args + [resolved_url]
        xbc.log(f"DEBUG: Launching mpv with command: {mpv_command}", level=xbc.LOGINFO)
        try:
            if sys.platform.startswith('win'):
                CREATE_NEW_CONSOLE = 0x00000010
                proc = subprocess.Popen(mpv_command, creationflags=CREATE_NEW_CONSOLE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
            else:
                proc = subprocess.Popen(mpv_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
            time.sleep(1)
            if proc.poll() is None:
                xbc.log(f"DEBUG: mpv process started with PID: {proc.pid}", level=xbc.LOGINFO)
                xbcgui.Dialog().notification("mpv", "Stream opened in mpv", xbcgui.NOTIFICATION_INFO, 2000)
            else:
                stdout, stderr = proc.communicate(timeout=5)
                xbc.log(f"DEBUG: mpv stdout: {stdout}", level=xbc.LOGINFO)
                xbc.log(f"DEBUG: mpv stderr: {stderr}", level=xbc.LOGINFO)
                xbc.log(f"DEBUG: mpv return code: {proc.returncode}", level=xbc.LOGERROR)
                raise subprocess.CalledProcessError(proc.returncode, mpv_command, stdout, stderr)
        except Exception as e:
            xbc.log("DEBUG: Failed to launch mpv", level=xbc.LOGERROR)
            xbc.log(f"DEBUG: mpv command: {mpv_command}", level=xbc.LOGERROR)
            if isinstance(e, subprocess.CalledProcessError):
                xbc.log(f"DEBUG: mpv exit code: {e.returncode}", level=xbc.LOGERROR)
                if getattr(e, 'stdout', None):
                    xbc.log(f"DEBUG: mpv failure stdout: {e.stdout}", level=xbc.LOGERROR)
                if getattr(e, 'stderr', None):
                    xbc.log(f"DEBUG: mpv failure stderr: {e.stderr}", level=xbc.LOGERROR)
            else:
                xbc.log(f"DEBUG: mpv exception type: {type(e).__name__}", level=xbc.LOGERROR)
                xbc.log(f"DEBUG: mpv exception: {str(e)}", level=xbc.LOGERROR)
                try:
                    import traceback
                    xbc.log(f"DEBUG: mpv traceback:\n{traceback.format_exc()}", level=xbc.LOGERROR)
                except Exception:
                    pass
            xbcgui.Dialog().ok("Error", f"Failed to launch mpv: {str(e)}")
        return



def _handle_choice_vlc(url, is_android, get_resolved_url):
    # Play in VLC (Windows)
    if is_android:
        xbcgui.Dialog().ok("VLC", "VLC external launch is configured for Windows path usage only.")
        return

    resolved_url, resolved_headers = get_resolved_url(url)
    if not resolved_url or not resolved_url.startswith("http"):
        xbcgui.Dialog().ok("Error", "Unable to resolve a valid stream URL for VLC.")
        return

    proxy_match = re.match(r"http://127\.0\.0\.1:\d+\?url=(http.*)", resolved_url)
    if proxy_match:
        resolved_url = urllib.parse.unquote(proxy_match.group(1))
        xbc.log(f"DEBUG: Decoded proxy URL for VLC: {resolved_url}", level=xbc.LOGINFO)

    vlc_path = xbcaddon.Addon().getSetting("vlc_path") or r"C:\Program Files\VideoLAN\VLC\vlc.exe"
    if not os.path.isfile(vlc_path):
        xbcgui.Dialog().ok("VLC Error", f"VLC not found at path:\n{vlc_path}")
        return

    vlc_command = [vlc_path]
    referer = resolved_headers.get('referer')
    user_agent = resolved_headers.get('user-agent')
    if referer:
        vlc_command += [f"--http-referrer={referer}"]
    if user_agent:
        vlc_command += [f"--http-user-agent={user_agent}"]
    vlc_command.append(resolved_url)

    try:
        CREATE_NEW_CONSOLE = 0x00000010
        subprocess.Popen(vlc_command, creationflags=CREATE_NEW_CONSOLE)
        xbcgui.Dialog().notification("VLC", "Stream sent to VLC", xbcgui.NOTIFICATION_INFO, 2500)
    except Exception as e:
        xbcgui.Dialog().ok("VLC Error", f"Failed to launch VLC: {str(e)}")
    return



def _handle_choice_mpc(url, is_android, get_resolved_url):
    # Play in MPC-HC (Windows)
    if is_android:
        xbcgui.Dialog().ok("MPC-HC", "MPC-HC external launch is available on Windows only.")
        return

    resolved_url, resolved_headers = get_resolved_url(url)
    if not resolved_url or not resolved_url.startswith("http"):
        xbcgui.Dialog().ok("Error", "Unable to resolve a valid stream URL for MPC-HC.")
        return

    proxy_match = re.match(r"http://127\.0\.0\.1:\d+\?url=(http.*)", resolved_url)
    if proxy_match:
        resolved_url = urllib.parse.unquote(proxy_match.group(1))
        xbc.log(f"DEBUG: Decoded proxy URL for MPC-HC: {resolved_url}", level=xbc.LOGINFO)

    mpc_hc_path = xbcaddon.Addon().getSetting("mpc_hc_path") or r"C:\Program Files\MPC-HC\mpc-hc64.exe"
    if not os.path.isfile(mpc_hc_path):
        xbcgui.Dialog().ok("MPC-HC Error", f"MPC-HC not found at path:\n{mpc_hc_path}")
        return

    mpc_command = [mpc_hc_path, resolved_url]
    try:
        CREATE_NEW_CONSOLE = 0x00000010
        subprocess.Popen(mpc_command, creationflags=CREATE_NEW_CONSOLE)
        if resolved_headers:
            xbcgui.Dialog().notification("MPC-HC", "Stream sent to MPC-HC (header-limited mode)", xbcgui.NOTIFICATION_INFO, 3000)
        else:
            xbcgui.Dialog().notification("MPC-HC", "Stream sent to MPC-HC", xbcgui.NOTIFICATION_INFO, 2500)
    except Exception as e:
        xbcgui.Dialog().ok("MPC-HC Error", f"Failed to launch MPC-HC: {str(e)}")
    return



def _handle_choice_android_external(url, is_android, get_resolved_url):
    # Android external player package (e.g., MX Player)
    if not is_android:
        xbcgui.Dialog().ok("Android External Player", "This option is intended for Android.")
        return

    resolved_url, resolved_headers = get_resolved_url(url)
    if not resolved_url or not resolved_url.startswith("http"):
        xbcgui.Dialog().ok("Error", "Unable to resolve a valid stream URL for Android external player.")
        return

    proxy_match = re.match(r"http://127\.0\.0\.1:\d+\?url=(http.*)", resolved_url)
    if proxy_match:
        resolved_url = urllib.parse.unquote(proxy_match.group(1))
        xbc.log(f"DEBUG: Decoded proxy URL for Android external player: {resolved_url}", level=xbc.LOGINFO)

    package = xbcaddon.Addon().getSetting("android_external_player_package") or "com.mxtech.videoplayer.ad"
    intent = xbcaddon.Addon().getSetting("android_external_player_intent") or "android.intent.action.VIEW"

    android_url = resolved_url
    if resolved_headers:
        header_params = "&".join([f"{k}={v}" for k, v in resolved_headers.items() if k.lower() in ["user-agent", "referer", "origin"]])
        if header_params:
            android_url = f"{resolved_url}|{header_params}"

    try:
        xbc.executebuiltin(f'StartAndroidActivity("{package}","{intent}","video/*","{android_url}")')
        xbcgui.Dialog().notification("Android Player", f"Stream sent to {package}", xbcgui.NOTIFICATION_INFO, 2500)
    except Exception as e:
        xbcgui.Dialog().ok("Android Player Error", f"Failed to launch external player app: {str(e)}")
    return
