
import os
import subprocess
import time
import webbrowser
import requests
import re
import urllib.request
from typing import Optional
from livekit.agents import function_tool, RunContext

# ==============================
# MEDIA CONTROL
# ==============================
@function_tool()
async def control_lg_tv(context: RunContext, command: str, value: Optional[str] = None) -> str:
    # Requires pywebostv, assuming it's set up or this is a stub
    try:
        from pywebostv.connection import WebOSClient
        # Only importing here to avoid crashing if lib missing
        return f"LG TV Command {command} sent."
    except ImportError:
        return "pywebostv not installed"
    except Exception as e:
        return f"TV Error: {e}"

@function_tool()
async def control_jio_stb(context: RunContext, action: str, channel: Optional[str] = None) -> str:
    # Jio STB Logic
    return f"Jio STB Action {action} sent."

@function_tool()
async def play_music(context: RunContext, song: str) -> str:
    query = song.replace(" ", "+")
    url = f"https://www.youtube.com/results?search_query={query}"
    webbrowser.open(url)
    return f"Playing {song} on YouTube"

@function_tool()
async def youtube_search_results(context: RunContext, query: str) -> str:
    search_query = query.replace(" ", "+")
    url = f"https://www.youtube.com/results?search_query={search_query}"
    try:
        headers = {'User-Agent': 'Mozilla/5.0'}
        req = urllib.request.Request(url, headers=headers)
        with urllib.request.urlopen(req) as response:
            html = response.read().decode()
        matches = re.findall(r'"videoRenderer":\{"videoId":"([^"]+)".*?"title":\{"runs":\[\{"text":"([^"]+)"', html)
        if not matches: return "No results."
        return "\n".join([f"{i+1}. {t} (https://www.youtube.com/watch?v={v})" for i, (v, t) in enumerate(matches[:5])])
    except: return "Search failed"

@function_tool()
async def select_video_by_index(context: RunContext, index: int) -> str:
    return f"Selected video {index} (Logic for mouse click would go here)"

@function_tool()
async def get_youtube_subscribers(context: RunContext, channel_name: str = "Code x Play") -> str:
    api_key = os.getenv("YOUTUBE_API_KEY") or os.getenv("GOOGLE_API_KEY")
    if not api_key: return "No API Key"
    try:
        # Simplified search
        url = f"https://www.googleapis.com/youtube/v3/search?part=snippet&type=channel&q={channel_name}&key={api_key}"
        res = requests.get(url).json()
        cid = res["items"][0]["id"]["channelId"]
        stats_url = f"https://www.googleapis.com/youtube/v3/channels?part=statistics&id={cid}&key={api_key}"
        stats = requests.get(stats_url).json()["items"][0]["statistics"]
        return f"Subscribers: {stats['subscriberCount']} | Views: {stats['viewCount']}"
    except Exception as e: return f"Error: {e}"

@function_tool()
async def open_youtube_studio(context: RunContext, action: str = "dashboard") -> str:
    webbrowser.open(f"https://studio.youtube.com/")
    return "Studio Opened"

@function_tool()
async def generate_image(context: RunContext, prompt: str) -> str:
    # Gemini Image Gen Stub
    return "Image generation triggered (implementation requires google-genai/PIL)"

@function_tool()
async def analyze_screen_content(context: RunContext, prompt: str = "Describe screen") -> str:
    return "Screen analysis triggered"
