#!/usr/bin/env python3
"""
Spotify 后台播放脚本 - 通过虚拟屏操作，不干扰主屏
用法: python3 spotify_play.py "歌名 歌手"

原理：
1. 杀掉 Spotify（确保能在虚拟屏启动）
2. 获取/创建虚拟屏
3. 在虚拟屏用 spotify:search:歌名 Deep Link 打开搜索页
4. 在虚拟屏点击第一个结果

2026-05-18 更新：支持虚拟屏，不抢占主屏
"""
import sys
import time
import re
import subprocess
from urllib.parse import quote

ADB = "adb -s localhost:15556"

def run(cmd):
    """执行命令并返回输出"""
    result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
    return result.stdout.strip()

def get_virtual_display():
    """获取虚拟屏 ID，没有就创建"""
    output = run(f"{ADB} shell dumpsys display | grep 'mDisplayId='")
    # 找非0的 display
    for line in output.split('\n'):
        match = re.search(r'mDisplayId=(\d+)', line)
        if match and match.group(1) != '0':
            return match.group(1)
    
    # 没有虚拟屏，创建一个
    print("创建虚拟屏...")
    subprocess.Popen(
        "ADB=/usr/bin/adb scrcpy --serial localhost:15556 --new-display=1080x2400 --render-driver=software",
        shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
    )
    time.sleep(4)
    
    # 重新获取
    output = run(f"{ADB} shell dumpsys display | grep 'mDisplayId='")
    for line in output.split('\n'):
        match = re.search(r'mDisplayId=(\d+)', line)
        if match and match.group(1) != '0':
            return match.group(1)
    return None

def play_song(query):
    print(f"搜索: {query}")
    
    # 1. 获取虚拟屏
    display_id = get_virtual_display()
    if display_id:
        print(f"使用虚拟屏 Display #{display_id}")
    else:
        print("警告: 没有虚拟屏，将在主屏操作")
        display_id = "0"
    
    # 2. 杀掉 Spotify（确保能在虚拟屏启动）
    run(f"{ADB} shell am force-stop com.spotify.music")
    time.sleep(1)
    
    # 3. 在虚拟屏打开 Spotify 搜索
    encoded_query = quote(query)
    if display_id != "0":
        cmd = f"{ADB} shell am start --display {display_id} -a android.intent.action.VIEW -d 'spotify:search:{encoded_query}'"
    else:
        cmd = f"{ADB} shell am start -a android.intent.action.VIEW -d 'spotify:search:{encoded_query}'"
    run(cmd)
    time.sleep(4)  # 等待搜索结果加载
    
    # 4. 在虚拟屏点击第一个结果
    # Spotify 搜索页布局：搜索栏(0-168) → 筛选栏(168-312) → 第一个结果(312-504)
    # 第一个结果中心点约 (540, 408)
    print("点击第一个结果...")
    if display_id != "0":
        run(f"{ADB} shell input touchscreen -d {display_id} tap 540 408")
    else:
        run(f"{ADB} shell input tap 540 408")
    time.sleep(2)
    
    # 5. 检查播放状态
    result = run(f"{ADB} shell dumpsys media_session | grep 'description='")
    if result:
        # 解析: description=歌名, 歌手, 专辑
        match = re.search(r'description=([^,]+),\s*([^,]+)', result)
        if match:
            print(f"正在播放: {match.group(1)} - {match.group(2)}")
        else:
            print(f"播放状态: {result}")

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("用法: python3 spotify_play.py '歌名 歌手'")
        print("示例: python3 spotify_play.py '晴天'")
        print("示例: python3 spotify_play.py '周杰伦 稻香'")
        sys.exit(1)
    
    query = " ".join(sys.argv[1:])
    play_song(query)
