#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
咪咕 miguSM 命令行工具（TgeBrowser + DrissionPage）：
  1. 传入手机号 → 新建浏览器、输入手机号、点击发送验证码
  2. 传入验证码 → 填写并提交

用法:
  set TGEBROWSER_API_KEY=你的API密钥
  python run_migu_cli.py --phone 13800138000
  python run_migu_cli.py --session-id <上一步返回的session_id> --code 123456
"""
from __future__ import annotations

import argparse
import os
import sys

# 确保 TgeBrowser 客户端和 migu 模块可导入
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from migu_miguSM_dp import (
    MIGU_HOME_URL,
    connect_dp_to_tgebrowser,
    connect_dp_to_ws,
    input_code_and_submit,
    input_phone_and_send_code,
)
from tgebrowser_client import TgeBrowserClient


def cmd_submit_phone(phone: str, url: str) -> str:
    """步骤一：输入手机号并发送验证码，返回 session_id（此处为 env_id 的字符串形式，用于后续填写验证码）。"""
    client = TgeBrowserClient()
    start_data = client.create_and_start(
        browser_name=f"miguSM_{phone[-4:]}",
        start_page_url=url,
    )
    port = start_data.get("port")
    ws = start_data.get("ws")
    env_id = start_data.get("envId")

    if port:
        page = connect_dp_to_tgebrowser(port)
    elif ws:
        page = connect_dp_to_ws(ws)
    else:
        raise RuntimeError("TgeBrowser 未返回 port 或 ws")

    input_phone_and_send_code(page, phone, url=url)
    print("输入电话号码成功，请查收短信验证码")
    # 保存到全局，供 submit_code 使用（CLI 模式只支持单次流程）
    cmd_submit_phone._page = page  # type: ignore
    cmd_submit_phone._client = client  # type: ignore
    cmd_submit_phone._env_id = env_id  # type: ignore
    return str(env_id or "ok")


def cmd_submit_code(code: str) -> None:
    """步骤二：填写验证码并提交。"""
    page = getattr(cmd_submit_phone, "_page", None)
    if not page:
        raise RuntimeError("请先执行步骤一：python run_migu_cli.py --phone 13800138000")
    result = input_code_and_submit(page, code)
    print(result.get("message", "验证码已填写"))


def main():
    parser = argparse.ArgumentParser(description="咪咕 miguSM 自动化 CLI")
    parser.add_argument("--phone", help="手机号码（步骤一）")
    parser.add_argument("--code", help="短信验证码（步骤二）")
    parser.add_argument("--interactive", "-i", action="store_true", help="步骤一后等待输入验证码（同一进程完成两步）")
    parser.add_argument("--url", default=MIGU_HOME_URL, help=f"目标页面，默认 {MIGU_HOME_URL}")
    args = parser.parse_args()

    if args.phone:
        cmd_submit_phone(args.phone, args.url)
        if args.interactive:
            code = input("请输入短信验证码: ").strip()
            if code:
                cmd_submit_code(code)
    elif args.code:
        cmd_submit_code(args.code)
    else:
        parser.print_help()
        print("\n示例:")
        print("  python run_migu_cli.py --phone 13800138000 -i   # 输入手机号后交互输入验证码")
        print("  python run_migu_cli.py --phone 13800138000      # 仅步骤一")
        print("  python run_migu_cli.py --code 123456            # 仅步骤二（需在 API 模式或同一进程的步骤一之后）")


if __name__ == "__main__":
    main()
