#!/usr/bin/env python3
"""
Twitter Cookie 获取工具
在本地电脑运行此脚本，登录 Twitter 后自动获取 Cookie 并上传到服务器

使用方法:
1. 安装依赖: pip install selenium requests python-dotenv
2. 修改 SERVER_URL 为你的服务器地址
3. 运行: python get_cookie_local.py

注意: 使用 Microsoft Edge 浏览器（需要安装 msedgedriver）
"""

import json
import os
import subprocess
import sys
import time

# ============== 配置 ==============
# 服务器地址（可通过 SERVER_URL 环境变量覆盖）
SERVER_URL = os.getenv("SERVER_URL", "https://agent.bitcoinrobot.cn")
# ==================================


def get_cookies_and_upload():
    """获取 Twitter cookies 并上传到服务器"""

    try:
        from selenium import webdriver
        from selenium.webdriver.edge.options import Options as EdgeOptions
        from selenium.webdriver.edge.service import Service as EdgeService
    except ImportError:
        print("请先安装 selenium: pip install selenium")
        sys.exit(1)

    try:
        import requests
    except ImportError:
        print("请先安装 requests: pip install requests")
        sys.exit(1)

    print("=" * 50)
    print("Twitter Cookie 获取工具 (Microsoft Edge)")
    print("=" * 50)
    print(f"\n服务器地址: {SERVER_URL}")
    print("\n步骤:")
    print("1. 脚本会打开 Microsoft Edge 浏览器")
    print("2. 请在浏览器中登录 Twitter")
    print("3. 登录成功后按 Enter 键")
    print("4. 脚本会自动获取 Cookie 并上传到服务器")
    print("\n" + "=" * 50)

    # Edge 配置
    options = EdgeOptions()
    options.add_argument("--disable-blink-features=AutomationControlled")
    options.add_experimental_option("excludeSwitches", ["enable-automation"])
    options.add_experimental_option("useAutomationExtension", False)

    # 尝试使用用户的 Edge 配置文件
    if sys.platform == "darwin":  # macOS
        edge_profile = os.path.expanduser(
            "~/Library/Application Support/Microsoft Edge"
        )
    elif sys.platform == "win32":  # Windows
        edge_profile = os.path.expanduser(
            "~\\AppData\\Local\\Microsoft\\Edge\\User Data"
        )
    else:  # Linux
        edge_profile = os.path.expanduser("~/.config/microsoft-edge")

    if os.path.exists(edge_profile):
        print(f"\n使用 Edge 配置文件: {edge_profile}")

        # 先关闭现有 Edge
        print("关闭现有 Edge 进程...")
        if sys.platform == "darwin":
            subprocess.run(["pkill", "-f", "Microsoft Edge"], capture_output=True)
        elif sys.platform == "win32":
            subprocess.run(["taskkill", "/F", "/IM", "msedge.exe"], capture_output=True)
        else:
            subprocess.run(["pkill", "-f", "msedge"], capture_output=True)
        time.sleep(2)

        options.add_argument(f"--user-data-dir={edge_profile}")
        options.add_argument("--profile-directory=Default")

    driver = None
    try:
        print("\n启动 Microsoft Edge...")
        driver = webdriver.Edge(options=options)

        # 隐藏 webdriver 标志
        driver.execute_cdp_cmd(
            "Page.addScriptToEvaluateOnNewDocument",
            {
                "source": "Object.defineProperty(navigator, 'webdriver', {get: () => undefined})"
            },
        )

        print("打开 Twitter 登录页面...")
        driver.get("https://x.com/i/flow/login")

        print("\n" + "=" * 50)
        print("请在浏览器中登录 Twitter")
        print("登录成功后，按 Enter 键继续...")
        print("=" * 50)
        input()

        # 刷新页面确保获取最新 cookies
        driver.get("https://x.com/home")
        time.sleep(3)

        print("\n获取 Cookies...")
        cookies = driver.get_cookies()

        # 过滤 Twitter cookies
        twitter_cookies = {}
        for c in cookies:
            if c["domain"] in [".x.com", "x.com", ".twitter.com", "twitter.com"]:
                twitter_cookies[c["name"]] = c["value"]

        auth_token = twitter_cookies.get("auth_token")
        ct0 = twitter_cookies.get("ct0")

        if not auth_token or not ct0:
            print("\n❌ 未能获取到必要的 Cookies (auth_token, ct0)")
            print("请确保已成功登录 Twitter")
            return False

        print(f"\n✅ 获取成功! 共 {len(twitter_cookies)} 个 Cookies")
        print(f"   auth_token: {auth_token[:20]}...")
        print(f"   ct0: {ct0[:20]}...")

        # 上传到服务器
        print(f"\n上传 Cookies 到服务器: {SERVER_URL}")

        try:
            response = requests.post(
                f"{SERVER_URL}/api/twikit-upload-cookies",
                json={"cookies": twitter_cookies},
                timeout=30,
            )

            if response.status_code == 200:
                result = response.json()
                if result.get("success"):
                    print("\n" + "=" * 50)
                    print("✅ Cookies 上传成功!")
                    print("=" * 50)
                    return True
                else:
                    print(f"\n❌ 上传失败: {result.get('error', '未知错误')}")
                    return False
            else:
                print(f"\n❌ 服务器错误: HTTP {response.status_code}")
                return False

        except requests.exceptions.ConnectionError:
            print(f"\n❌ 无法连接到服务器: {SERVER_URL}")
            print("请检查服务器是否运行中")

            # 保存到本地文件作为备份
            local_file = "twitter_cookies.json"
            with open(local_file, "w") as f:
                json.dump(twitter_cookies, f, indent=2)
            print(f"\n💾 Cookies 已保存到本地文件: {local_file}")
            print("你可以手动将此文件上传到服务器")
            return False

    except Exception as e:
        print(f"\n❌ 错误: {e}")
        import traceback

        traceback.print_exc()
        return False

    finally:
        if driver:
            print("\n关闭浏览器...")
            driver.quit()


if __name__ == "__main__":
    # 检查是否提供了服务器地址参数
    if len(sys.argv) > 1:
        SERVER_URL = sys.argv[1]

    success = get_cookies_and_upload()

    print("\n" + "=" * 50)
    if success:
        print("🎉 授权完成! 现在可以使用 Twikit 发推了")
    else:
        print("❌ 授权失败，请重试")
    print("=" * 50)

    input("\n按 Enter 键退出...")
