# -*- coding: utf-8 -*-
"""BSPHP 卡模式演示。"""

from __future__ import annotations

import sys
from pathlib import Path


ROOT = Path(__file__).resolve().parent.parent / "bsphp.Python.car"
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_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 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,
    )
    client = BSPHPClient(cfg, get_machine_code)

    print("BSPHP 卡模式 Python 命令行演示（无 GUI）")
    print("流程：bootstrap -> 菜单（login.ic、机器码账号、充值等）")
    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 已就绪。")
    notice = client.get_notice()
    if notice.code is not None:
        print("公告 gg.in:", notice.data)
    print()

    while True:
        print("---- 菜单 ----")
        print("1 卡密登录（login.ic）")
        print("2 机器码账号：AddCardFeatures.key.ic + login.ic")
        print("3 刷新到期（getdate.ic）")
        print("4 网络测试（internet.in）")
        print("5 版本（v.in）")
        print("6 机器码充值（chong.ic）")
        print("7 注销并重新取 SeSsL（cancellation.ic + BSphpSeSsL.in）")
        print("0 退出")
        choice = read_line("选: ")
        if choice in {"", "0"}:
            break

        if choice == "1":
            icid = read_line("卡串 icid: ")
            icpwd = read_line("卡密码（可无）: ")
            r = client.login_ic(icid, icpwd, client.machine_code, client.machine_code)
            show_result("login.ic", r)
            if r.code in SUCCESS_CODES:
                d = client.get_date_ic()
                show_result("getdate.ic", d)
        elif choice == "2":
            account = read_line("机器码账号（carid）: ")
            f = client.add_card_features(account, client.machine_code, client.machine_code)
            show_result("AddCardFeatures.key.ic", f)
            o = client.login_ic(account, "", client.machine_code, client.machine_code)
            show_result("login.ic", o)
        elif choice == "3":
            show_result("getdate.ic", client.get_date_ic())
        elif choice == "4":
            print("网络正常" if client.connect() else "网络异常")
        elif choice == "5":
            show_result("v.in", client.get_version())
        elif choice == "6":
            icid = read_line("机器码账号 icid: ")
            ka = read_line("充值卡号 ka: ")
            pwd = read_line("充值密码 pwd（可无）: ")
            show_result("chong.ic", client.recharge_card(icid, ka, pwd))
        elif choice == "7":
            show_result("cancellation.ic", client.logout())
        else:
            print("无效选项")
        print()

    return 0


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