"""
首次认证脚本

通过交互式输入邮箱验证码完成认证，将 UserData 缓存到本地 JSON 文件。
"""

import asyncio
import json
from pathlib import Path

from roborock.web_api import RoborockApiClient


CACHE_DIR = Path.home() / ".cache" / "roborock-mcp"
TOKEN_FILE = CACHE_DIR / "user_data.json"


async def setup():
    """交互式认证流程"""
    print("=" * 50)
    print(" Roborock MCP 首次认证")
    print("=" * 50)

    email = input("\n请输入 Roborock 账户邮箱: ").strip()
    if not email:
        print("错误：邮箱不能为空")
        return

    web_api = RoborockApiClient(username=email)

    print(f"\n正在向 {email} 发送验证码...")
    try:
        await web_api.request_code_v4()
    except Exception as e:
        print(f"发送验证码失败: {e}")
        return

    print("验证码已发送，请查收邮件")

    code = input("\n请输入收到的验证码: ").strip()
    if not code:
        print("错误：验证码不能为空")
        return

    print("正在验证...")
    try:
        user_data = await web_api.code_login_v4(code)
    except Exception as e:
        print(f"验证失败: {e}")
        return

    # 保存缓存（不保存 base_url，让 SDK 自动发现）
    CACHE_DIR.mkdir(parents=True, exist_ok=True)
    data = {
        "email": email,
        "user_data": user_data.as_dict(),
    }
    with open(TOKEN_FILE, "w") as f:
        json.dump(data, f, indent=2)

    print(f"\n认证成功！")
    print(f"缓存已保存到: {TOKEN_FILE}")
    print("\n现在可以启动 MCP server 了：")
    print("  roborock-mcp")


def main():
    asyncio.run(setup())


if __name__ == "__main__":
    main()
