#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""一次性把舊版 Google Drive pickle token 轉成 JSON token。

此腳本只供受控維運使用。pickle 可能執行任意程式碼，所以必須用明確
環境變數批准，且只在可信任的正式 config 來源上執行。
"""

import json
import os
import pickle
from pathlib import Path


LEGACY_TOKEN_FILE = Path(os.getenv("GOOGLE_DRIVE_LEGACY_TOKEN_FILE", "config/google_token.pickle"))
TARGET_TOKEN_FILE = Path(os.getenv("GOOGLE_DRIVE_TOKEN_FILE", "config/google_token.json"))
ALLOW_ENV = "MOMO_ALLOW_LEGACY_GOOGLE_TOKEN_PICKLE_MIGRATION"


def _allowed() -> bool:
    return os.getenv(ALLOW_ENV, "").strip().lower() in {"1", "true", "yes", "on"}


def main() -> int:
    if not _allowed():
        print(f"拒絕執行：請先設定 {ALLOW_ENV}=true。")
        return 2

    if not LEGACY_TOKEN_FILE.exists():
        print(f"找不到舊版授權檔：{LEGACY_TOKEN_FILE}")
        return 1

    if TARGET_TOKEN_FILE.exists():
        print(f"JSON 授權檔已存在：{TARGET_TOKEN_FILE}")
        return 0

    with LEGACY_TOKEN_FILE.open("rb") as handle:
        credentials = pickle.load(handle)

    if not hasattr(credentials, "to_json"):
        print("舊版授權檔格式不支援轉換。")
        return 1

    token_payload = json.loads(credentials.to_json())
    TARGET_TOKEN_FILE.parent.mkdir(parents=True, exist_ok=True)
    tmp_path = TARGET_TOKEN_FILE.with_name(f"{TARGET_TOKEN_FILE.name}.tmp")
    tmp_path.write_text(json.dumps(token_payload, ensure_ascii=False, indent=2), encoding="utf-8")
    os.chmod(tmp_path, 0o600)
    os.replace(tmp_path, TARGET_TOKEN_FILE)
    print(f"已產生 JSON 授權檔：{TARGET_TOKEN_FILE}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
