from __future__ import annotations

import json
import os
import sys
import time

_TOKEN_DIR = os.environ.get(
    "FEISHU_TOKEN_DIR",
    os.path.join(os.path.expanduser("~"), ".config", "feishu-operator"),
)
_TOKEN_FILE = os.path.join(_TOKEN_DIR, "credentials.json")


def save_token(
    access_token: str,
    refresh_token: str,
    expires_at: float,
    token_type: str = "Bearer",
    scopes: list[str] | None = None,
) -> bool:
    try:
        os.makedirs(_TOKEN_DIR, mode=0o700, exist_ok=True)
        existing: dict = {}
        if os.path.exists(_TOKEN_FILE):
            try:
                with open(_TOKEN_FILE, "r", encoding="utf-8") as f:
                    existing = json.load(f)
            except Exception:
                pass
        data = {
            "access_token": access_token,
            "refresh_token": refresh_token,
            "expires_at": expires_at,
            "token_type": token_type,
            "scopes": scopes if scopes is not None else existing.get("scopes", []),
        }
        with open(_TOKEN_FILE, "w", encoding="utf-8") as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
        os.chmod(_TOKEN_FILE, 0o600)
        return True
    except Exception as e:
        print(f"❌ 保存凭证失败: {e}", file=sys.stderr)
        return False


def load_token() -> tuple[str | None, str | None, float]:
    try:
        if not os.path.exists(_TOKEN_FILE):
            return None, None, 0.0
        with open(_TOKEN_FILE, "r", encoding="utf-8") as f:
            data = json.load(f)
        return data.get("access_token"), data.get("refresh_token"), float(data.get("expires_at", 0))
    except Exception as e:
        print(f"⚠️  加载凭证失败: {e}", file=sys.stderr)
        return None, None, 0.0


def load_scopes() -> list[str]:
    try:
        if not os.path.exists(_TOKEN_FILE):
            return []
        with open(_TOKEN_FILE, "r", encoding="utf-8") as f:
            data = json.load(f)
        return data.get("scopes", [])
    except Exception:
        return []


def delete_token() -> bool:
    try:
        if os.path.exists(_TOKEN_FILE):
            os.remove(_TOKEN_FILE)
            return True
        return False
    except Exception as e:
        print(f"⚠️  删除凭证失败: {e}", file=sys.stderr)
        return False


def is_token_expired(expires_at: float, buffer_seconds: int = 300) -> bool:
    return time.time() >= (expires_at - buffer_seconds)
