from __future__ import annotations

import argparse
import getpass
import json
import socket
import sys
import urllib.error
import urllib.request
import webbrowser
from pathlib import Path


PLUGIN_ROOT = Path(__file__).resolve().parent
sys.path.insert(0, str(PLUGIN_ROOT / "mcp"))

from yoho_credentials import CredentialError, save_api_key  # noqa: E402


CONFIG_SITE = "https://yohohoho.asia/"
VALIDATE_URL = "https://yohohoho.asia/api/v1/validate"


def validate_api_key(api_key: str) -> None:
    request = urllib.request.Request(
        VALIDATE_URL,
        headers={
            "Authorization": f"Bearer {api_key}",
            "Accept": "application/json",
            "User-Agent": "YOHOHOHO-Image-Installer/1.0",
        },
        method="GET",
    )
    try:
        with urllib.request.urlopen(request, timeout=15) as response:
            payload = json.loads(response.read().decode("utf-8"))
    except urllib.error.HTTPError as exc:
        if exc.code in (401, 403):
            raise CredentialError("API Key 无效或无权访问，请检查后重试。") from exc
        raise CredentialError(f"配置服务返回错误（HTTP {exc.code}），请稍后重试。") from exc
    except (TimeoutError, socket.timeout, urllib.error.URLError) as exc:
        raise CredentialError("无法连接 YOHOHOHO 配置服务，请检查网络后重试。") from exc
    except (UnicodeDecodeError, json.JSONDecodeError) as exc:
        raise CredentialError("配置服务返回了无效数据，请稍后重试。") from exc
    if not isinstance(payload, dict) or payload.get("ok") is not True:
        raise CredentialError("API Key 验证失败，请检查后重试。")


def main() -> int:
    parser = argparse.ArgumentParser(description="配置 YOHOHOHO 生图插件")
    parser.add_argument("--no-browser", action="store_true")
    args = parser.parse_args()
    print("\n[YOHOHOHO] 生图插件 API Key 配置")
    print("Key 会使用 Windows DPAPI 加密后保存在当前用户目录，不会写入插件文件。")
    api_key = getpass.getpass("请粘贴 YOHOHOHO API Key（输入不会显示）：").strip()
    if not api_key:
        print("[YOHOHOHO] API Key 不能为空。", file=sys.stderr)
        return 1
    try:
        print("[YOHOHOHO] 正在验证 API Key...")
        validate_api_key(api_key)
        path = save_api_key(api_key)
    except CredentialError as exc:
        print(f"[YOHOHOHO] 配置失败：{exc}", file=sys.stderr)
        return 1
    finally:
        api_key = ""
    print(f"[YOHOHOHO] API Key 已安全保存：{path}")
    print(f"[YOHOHOHO] 请在 {CONFIG_SITE} 选择生图平台和模型。")
    if not args.no_browser:
        webbrowser.open(CONFIG_SITE)
    return 0


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