"""
Google Calendar OAuth 授权 & token.json 生成工具。

用法：
  python3 scripts/setup_gcal_token.py --client-id YOUR_ID --client-secret YOUR_SECRET

完成浏览器授权后，自动生成 ~/.config/gcalcli/token.json（sophnet-schedule 所需格式）。
"""

from __future__ import annotations

import argparse
import json
import os
import sys
from pathlib import Path

try:
    from google_auth_oauthlib.flow import InstalledAppFlow
except ImportError:
    print("缺少依赖，请先安装：pip3 install google-auth-oauthlib")
    sys.exit(1)

SCOPES = ["https://www.googleapis.com/auth/calendar"]
TOKEN_DIR = Path.home() / ".config" / "gcalcli"
TOKEN_PATH = TOKEN_DIR / "token.json"


def main():
    parser = argparse.ArgumentParser(description="生成 Google Calendar token.json")
    parser.add_argument("--client-id", required=True, help="OAuth Client ID")
    parser.add_argument("--client-secret", required=True, help="OAuth Client Secret")
    parser.add_argument(
        "--output", default=str(TOKEN_PATH), help=f"输出路径 (默认 {TOKEN_PATH})"
    )
    args = parser.parse_args()

    flow = InstalledAppFlow.from_client_config(
        client_config={
            "installed": {
                "client_id": args.client_id,
                "client_secret": args.client_secret,
                "auth_uri": "https://accounts.google.com/o/oauth2/auth",
                "token_uri": "https://oauth2.googleapis.com/token",
                "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
                "redirect_uris": ["http://localhost"],
            }
        },
        scopes=SCOPES,
    )

    print("即将打开浏览器进行 Google 授权...")
    print("如果浏览器没有自动打开，请复制下方链接手动打开。\n")

    try:
        credentials = flow.run_local_server(
            port=0, open_browser=False, prompt="consent"
        )
    except Exception as e:
        print(f"\n授权失败: {e}")
        print("\n常见原因：")
        print("  1. OAuth 客户端类型必须是 '桌面应用'（Desktop app）")
        print("  2. Google Calendar API 未启用")
        print("  3. 你的邮箱未添加为测试用户（如果 App 未发布）")
        sys.exit(1)

    token_data = {
        "client_id": args.client_id,
        "client_secret": args.client_secret,
        "refresh_token": credentials.refresh_token,
        "token": credentials.token,
        "token_uri": "https://oauth2.googleapis.com/token",
    }

    output_path = Path(args.output)
    output_path.parent.mkdir(parents=True, exist_ok=True)
    with open(output_path, "w") as f:
        json.dump(token_data, f, indent=2)

    print(f"\n授权成功！Token 已保存到: {output_path}")
    print("sophnet-schedule 现在可以正常访问 Google Calendar 了。")


if __name__ == "__main__":
    main()
