#!/usr/bin/env python3
"""AIPPT-NEW 鉴权模块：自动获取并保存 Docmee API Key。

API Key 解析顺序：
  1. 环境变量 DOCMEE_API_KEY
  2. 技能目录中的本地文件 docmee_api_key.json

命令行：
  python auth.py
  python auth.py --set-key "ak_xxx"
  python auth.py --clear-key
  python auth.py --show-path
"""

from __future__ import annotations

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


SKILL_DIR = Path(__file__).resolve().parent.parent
API_KEY_FILE = SKILL_DIR / "docmee_api_key.json"
REGISTER_URL = "https://docmee.cn/open"


def get_api_key_file_path() -> Path:
    return API_KEY_FILE


def _read_local_api_key() -> str:
    path = get_api_key_file_path()
    try:
        with path.open("r", encoding="utf-8") as file:
            payload = json.load(file)
    except FileNotFoundError:
        return ""
    except (OSError, json.JSONDecodeError):
        return ""
    return str(payload.get("apiKey", "")).strip()


def save_api_key(api_key: str) -> Path:
    value = api_key.strip()
    if not value:
        raise RuntimeError("API Key 为空，无法保存")

    path = get_api_key_file_path()
    payload = {"apiKey": value}
    with path.open("w", encoding="utf-8") as file:
        json.dump(payload, file, ensure_ascii=False, indent=2)
        file.write("\n")

    try:
        path.chmod(stat.S_IRUSR | stat.S_IWUSR)
    except OSError:
        pass
    return path


def clear_api_key() -> bool:
    path = get_api_key_file_path()
    if not path.exists():
        return False
    path.unlink()
    return True


def resolve_api_key() -> str:
    """自动获取 API Key：优先环境变量，其次技能目录本地文件。"""
    key = os.environ.get("DOCMEE_API_KEY", "").strip()
    if key:
        return key

    key = _read_local_api_key()
    if key:
        return key

    raise RuntimeError(
        "未找到 DOCMEE_API_KEY。请先向用户索取文多多 API Key 并执行 "
        f'`uv run scripts/auth.py --set-key "ak_xxx"` 保存。注册链接：{REGISTER_URL}'
    )


def main() -> int:
    parser = argparse.ArgumentParser(description="AIPPT-NEW 鉴权工具")
    parser.add_argument("--set-key", dest="set_key", default=None, help="保存 Docmee API Key")
    parser.add_argument("--clear-key", action="store_true", help="删除已保存的 Docmee API Key")
    parser.add_argument("--show-path", action="store_true", help="显示本地 API Key 文件路径")
    args = parser.parse_args()

    try:
        if args.show_path:
            print(get_api_key_file_path())
            return 0

        if args.clear_key:
            deleted = clear_api_key()
            if deleted:
                print(f"已删除本地 API Key 文件: {get_api_key_file_path()}")
            else:
                print(f"本地 API Key 文件不存在: {get_api_key_file_path()}")
            return 0

        if args.set_key is not None:
            path = save_api_key(args.set_key)
            print(f"API Key 保存成功: {path}")
            return 0

        api_key = resolve_api_key()
        print(f"API Key 获取成功: {api_key[:8]}...{api_key[-4:]}")
        return 0
    except RuntimeError as exc:
        print(f"错误：{exc}", file=sys.stderr)
        return 1


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