#!/usr/bin/env python3
"""
后台发微信消息 - 使用 uiautomator2 的 set_text，不影响主屏输入
"""
import sys
import time
import subprocess

# 参数
contact = sys.argv[1] if len(sys.argv) > 1 else "文件传输助手"
message = sys.argv[2] if len(sys.argv) > 2 else "虾宝后台测试"

SERIAL = "localhost:15556"

def adb(cmd):
    result = subprocess.run(
        ["adb", "-s", SERIAL, "shell", cmd],
        capture_output=True, text=True, timeout=30
    )
    return result.stdout.strip()

def get_display_id():
    """获取虚拟屏 ID"""
    output = adb("dumpsys display | grep 'Display Id'")
    for line in output.split('\n'):
        if 'Display Id=' in line:
            did = int(line.split('=')[1].strip())
            if did != 0:
                return did
    return None

def create_virtual_display():
    """创建虚拟屏"""
    import os
    env = os.environ.copy()
    env["ADB"] = "/usr/bin/adb"
    subprocess.Popen(
        ["/usr/local/bin/scrcpy", "--serial", SERIAL, "--new-display=1080x2400", "--render-driver=software"],
        stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env
    )
    time.sleep(3)
    return get_display_id()

def tap(display_id, x, y):
    adb(f"input touchscreen -d {display_id} tap {x} {y}")

def set_text_via_u2(text):
    """用 uiautomator2 设置文本"""
    import uiautomator2 as u2
    d = u2.connect(SERIAL)
    # 找到当前焦点的输入框并设置文本
    d(focused=True).set_text(text)

def main():
    print(f"[开始] 发送给 {contact}: {message}")
    
    # 确保虚拟屏
    did = get_display_id()
    if not did:
        print("[创建虚拟屏]")
        did = create_virtual_display()
    if not did:
        print("[错误] 无法创建虚拟屏")
        return
    print(f"[虚拟屏] Display {did}")
    
    # 启动微信
    adb(f"am start --display {did} -n com.tencent.mm/.ui.LauncherUI")
    time.sleep(2)
    
    # 点击搜索
    tap(did, 920, 150)
    time.sleep(0.5)
    
    # 输入联系人
    set_text_via_u2(contact)
    time.sleep(1.5)
    
    # 点击搜索结果
    tap(did, 540, 300)
    time.sleep(1)
    
    # 点击输入框
    tap(did, 540, 2280)
    time.sleep(0.3)
    
    # 输入消息
    set_text_via_u2(message)
    time.sleep(0.3)
    
    # 点击发送
    tap(did, 980, 2096)
    time.sleep(0.5)
    
    print(f"[完成] 已发送")

if __name__ == "__main__":
    main()
