import os
import sys
import json
import uuid
import platform
import hashlib
import pathlib
import urllib.request
import urllib.error

# 授权服务器地址
LICENSE_SERVER_URL = "http://43.167.210.121:8000"

def get_machine_id() -> str:
    """获取当前机器唯一标识"""
    parts = [
        platform.node(),
        platform.machine(),
        platform.processor(),
        str(uuid.getnode()),
    ]
    raw = "|".join(parts)
    return hashlib.sha256(raw.encode()).hexdigest()[:32]

def _get_activated_key_path() -> pathlib.Path:
    """获取本地已激活卡密的存储路径"""
    if getattr(sys, 'frozen', False) and sys.platform == 'darwin':
        base = pathlib.Path.home() / "Library" / "Application Support" / "GoldAutoTrade"
        base.mkdir(parents=True, exist_ok=True)
        return base / "activated.key"
    # 开发环境或非 macOS
    from config_manager import get_app_dir
    return get_app_dir() / "activated.key"

def get_activated_key() -> str:
    """读取本地已激活的卡密"""
    key_path = _get_activated_key_path()
    if key_path.exists():
        with open(key_path, "r", encoding="utf-8") as f:
            return f.read().strip()
    return ""

def activate_key(key: str) -> tuple:
    """
    激活：保存卡密到本地，并联网验证
    返回 (success: bool, message: str)
    """
    if not key or len(key.strip()) < 4:
        return False, "卡密格式无效"

    machine_id = get_machine_id()

    try:
        data = json.dumps({
            "license_key": key.strip(),
            "machine_id": machine_id
        }).encode("utf-8")

        req = urllib.request.Request(
            f"{LICENSE_SERVER_URL}/api/verify",
            data=data,
            headers={"Content-Type": "application/json"}
        )
        with urllib.request.urlopen(req, timeout=8) as response:
            res_data = json.loads(response.read().decode())

        if res_data.get("status") == "active":
            # 保存到本地
            key_path = _get_activated_key_path()
            key_path.parent.mkdir(parents=True, exist_ok=True)
            with open(key_path, "w", encoding="utf-8") as f:
                f.write(key.strip())
            return True, "激活成功"
        else:
            return False, f"验证拒绝: {res_data.get('message', '未知错误')}"

    except urllib.error.URLError:
        return False, "无法连接授权服务器，请检查网络"
    except Exception as e:
        return False, f"激活异常: {e}"

def is_activated() -> bool:
    """检查是否已激活（有本地保存的有效卡密）"""
    key = get_activated_key()
    if not key:
        return False
    # 本地有 key 认为激活（服务器会在启动时验证）
    return True

def verify_license_online() -> tuple:
    """
    联网授权验证（有本地激活 key 才验证）
    """
    key = get_activated_key()
    if not key:
        # 未激活，但不再阻止启动，由前端显示激活界面
        return True, "未激活（前端显示激活界面）"

    machine_id = get_machine_id()

    try:
        data = json.dumps({
            "license_key": key,
            "machine_id": machine_id
        }).encode("utf-8")

        req = urllib.request.Request(
            f"{LICENSE_SERVER_URL}/api/verify",
            data=data,
            headers={"Content-Type": "application/json"}
        )
        with urllib.request.urlopen(req, timeout=8) as response:
            res_data = json.loads(response.read().decode())

        if res_data.get("status") == "active":
            return True, "授权有效"
        else:
            return False, f"授权已失效: {res_data.get('message', '请联系续费')}"

    except Exception as e:
        # 网络异常时容错（本地已有激活 key，允许启动）
        return True, f"授权服务器连接异常，临时放行: {e}"
