# -*- coding: utf-8 -*-
"""BSPHP 用户模式 Python 命令行演示（无 GUI，参考 gc++ user）。"""

from __future__ import annotations

import sys
from pathlib import Path


ROOT = Path(__file__).resolve().parent
REQUIRED_FILES = ("config.py", "bsphp_client.py", "machine_code.py")
MENU_TEXT = (
    "---- 菜单 ----\n"
    "1 用户登录（login.lg）\n"
    "2 刷新到期（vipdate.lg）\n"
    "3 网络测试（internet.in）\n"
    "4 版本（v.in）\n"
    "5 注销并重新取 SeSsL（cancellation.lg + BSphpSeSsL.in）\n"
    "6 充值续期（chong.lg）\n"
    "0 退出"
)


def ensure_required_files() -> None:
    missing = [name for name in REQUIRED_FILES if not (ROOT / name).exists()]
    if not missing:
        return
    print(f"当前目录 {ROOT} 缺少运行所需文件，请手动复制后再运行：")
    for name in missing:
        print(f"  - {name}")
    raise SystemExit(1)


ensure_required_files()
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

from bsphp_client import BSPHPClient, ClientConfig, InitFailedError  # noqa: E402
from config import (  # noqa: E402
    BSPHP_CLIENT_PUBLIC_KEY,
    BSPHP_CODE_URL_PREFIX,
    BSPHP_MUTUAL_KEY,
    BSPHP_SERVER_PRIVATE_KEY,
    BSPHP_URL,
)
from machine_code import get_machine_code  # noqa: E402


SUCCESS_CODES = {1011, 1081, 9908}


def read_line(prompt: str) -> str:
    try:
        return input(prompt).strip()
    except EOFError:
        return ""


def show_result(name: str, r) -> None:
    print(f"{name}:")
    print(f"  code = {r.code}")
    print(f"  data = {r.data}")


def read_yes_no(prompt: str) -> bool:
    return read_line(prompt) in {"1", "y", "Y"}


def main() -> int:
    cfg = ClientConfig(
        url=BSPHP_URL,
        mutual_key=BSPHP_MUTUAL_KEY,
        server_private_key=BSPHP_SERVER_PRIVATE_KEY,
        client_public_key=BSPHP_CLIENT_PUBLIC_KEY,
        code_url_prefix=BSPHP_CODE_URL_PREFIX,
    )
    client = BSPHPClient(cfg, get_machine_code)

    print("BSPHP 用户模式 Python 命令行演示（无 GUI）")
    print("流程：bootstrap -> login.lg（user/pwd/coode）-> vipdate.lg 等")
    print()
    print("本机机器码 key/maxoror:", client.machine_code)
    print()
    print("正在 bootstrap（internet.in + BSphpSeSsL.in）...")
    try:
        client.bootstrap()
    except InitFailedError as e:
        print("初始化失败：", e, sep="")
        return 1

    print("初始化成功，SeSsL 已就绪。")
    print("验证码 URL（可浏览器打开查看图片）:", client.code_image_url)
    notice = client.get_notice()
    if notice.code is not None:
        print("公告 gg.in:", notice.data)
    print()

    try:
        while True:
            print(MENU_TEXT)
            choice = read_line("选: ")
            if choice in {"", "0"}:
                break

            if choice == "1":
                user = read_line("用户名 user: ")
                pwd = read_line("密码 pwd: ")
                code = read_line("登录验证码 coode（无图形验证可留空）: ")
                r = client.login(user, pwd, code, client.machine_code, client.machine_code)
                show_result("login.lg", r)
                if r.code in SUCCESS_CODES:
                    show_result("vipdate.lg", client.get_end_time())
            elif choice == "2":
                show_result("vipdate.lg", client.get_end_time())
            elif choice == "3":
                print("网络正常" if client.connect() else "网络异常")
            elif choice == "4":
                show_result("v.in", client.get_version())
            elif choice == "5":
                show_result("cancellation.lg", client.logout())
            elif choice == "6":
                user = read_line("账号 user: ")
                userpwd = read_line("账号密码 userpwd: ")
                userset = read_yes_no("是否修改用户资料 userset（1 是 / 0 否）: ")
                ka = read_line("充值卡号 ka: ")
                kpwd = read_line("卡密码 pwd（可无）: ")
                show_result("chong.lg", client.pay(user, userpwd, userset, ka, kpwd))
            else:
                print("无效选项")
            print()
    except KeyboardInterrupt:
        print("\n已取消，退出。")
        return 130

    return 0


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