
import os
import subprocess
import time
from livekit.agents import function_tool, RunContext

def adb_cmd(cmd_list):
    # Locate ADB
    base_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    adb_path = os.path.join(base_path, "platform-tools", "adb.exe")
    if not os.path.exists(adb_path): adb_path = "adb"
    
    full_cmd = [adb_path] + cmd_list
    return subprocess.run(full_cmd, capture_output=True, text=True)

@function_tool()
async def play_game_action(context: RunContext, action: str, params: str = "") -> str:
    """
    Executes specific ADB actions for game automation.
    Actions: 
    - click x,y: Click at coordinates
    - swipe x1,y1,x2,y2,duration: Swipe from start to end
    - key keycode: Send a specific keycode (e.g. 66 for Enter)
    - text string: Type text
    - home: Go to home screen
    - back: Press back button
    """
    try:
        if action == "click":
            x, y = params.split(",")
            adb_cmd(["shell", "input", "tap", x.strip(), y.strip()])
        elif action == "swipe":
            x1, y1, x2, y2, d = params.split(",")
            adb_cmd(["shell", "input", "swipe", x1.strip(), y1.strip(), x2.strip(), y2.strip(), d.strip()])
        elif action == "key":
            adb_cmd(["shell", "input", "keyevent", params.strip()])
        elif action == "text":
            adb_cmd(["shell", "input", "text", params.strip()])
        elif action == "home":
            adb_cmd(["shell", "input", "keyevent", "3"])
        elif action == "back":
            adb_cmd(["shell", "input", "keyevent", "4"])
        else:
            return f"Unknown action: {action}"
        
        return f"Action {action} executed with params {params}"
    except Exception as e:
        return f"ADB Error: {e}"

@function_tool()
async def play_game_scenario(context: RunContext, scenario: str) -> str:
    """
    Executes a predefined sequence of actions (scenario) for a game.
    Example: 'collect_daily_reward', 'start_match', 'next_level'
    """
    if scenario == "collect_daily_reward":
        # Simulate a typical sequence
        adb_cmd(["shell", "input", "tap", "500", "500"]) # Center click
        time.sleep(2)
        adb_cmd(["shell", "input", "tap", "200", "800"]) # Close button
        return "Scenario collect_daily_reward completed."
    elif scenario == "start_match":
        adb_cmd(["shell", "input", "tap", "800", "900"]) # Start button
        return "Scenario start_match initiated."
    elif scenario == "next_level":
        adb_cmd(["shell", "input", "tap", "900", "500"]) # Next level button
        return "Scenario next_level executed."
    
    return f"Scenario {scenario} not implemented."

@function_tool()
async def get_screen_info_via_adb(context: RunContext) -> str:
    """Gets screen resolution and current activity for context."""
    res = adb_cmd(["shell", "wm", "size"])
    activity = adb_cmd(["shell", "dumpsys", "window", "|", "grep", "mCurrentFocus"])
    return f"Screen: {res.stdout.strip()}, Activity: {activity.stdout.strip()}"
