#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
通用许可证验证装饰器
支持 API 接口，包含功能：check, deactivate, renew, activate, validate
"""

import json
import hashlib
import time
import secrets
import requests
import platform
import uuid
import os
import sys
import webbrowser
import pickle
from datetime import datetime, timedelta
import tkinter as tk
from tkinter import messagebox, ttk
import customtkinter as ctk
from functools import wraps


class LicenseValidator:
    """许可证验证器核心类"""

    def __init__(self, project_id, project_api_secret, app_name="软件名称", cache_suffix=""):
        self.api_base = "http://aps.com/api.php"
        self.project_id = project_id
        self.project_api_secret = project_api_secret
        self.app_name = app_name
        self.cache_suffix = cache_suffix
        self.cache_dir = "db"
        if cache_suffix:
            self.cache_file = os.path.join(self.cache_dir, f"license_cache_{cache_suffix}.bin")
            self.cache_file_json = os.path.join(self.cache_dir, f"license_cache_{cache_suffix}.json")
        else:
            self.cache_file = os.path.join(self.cache_dir, "license_cache.bin")
            self.cache_file_json = os.path.join(self.cache_dir, "license_cache.json")
        self.device_info = self.get_device_info()
        self.is_validated = False
        self.license_info = {}
        self.license_code = None
        self.is_vip = False
        self.vip_info = {}
        self.permissions = {}  # 自定义权限配置
        self._ensure_cache_dir()
        self.encryption_key = self._generate_encryption_key()

    def _ensure_cache_dir(self):
        if not os.path.exists(self.cache_dir):
            os.makedirs(self.cache_dir, exist_ok=True)

    def get_device_info(self):
        try:
            system_info = f"{platform.node()}{platform.machine()}{platform.processor()}{platform.system()}{platform.version()}"
            device_fingerprint = hashlib.md5(system_info.encode()).hexdigest()
            try:
                mac = uuid.getnode()
                mac_address = ':'.join(['{:02x}'.format((mac >> elements) & 0xff)
                                        for elements in range(0, 8 * 6, 8)][::-1])
            except:
                mac_address = "00:11:22:33:44:55"
            hardware_id_source = f"{platform.node()}{platform.machine()}{platform.processor()}"
            hardware_id = hashlib.sha256(hardware_id_source.encode()).hexdigest()[:32]
            return {
                'device_fingerprint': device_fingerprint,
                'mac_address': mac_address,
                'hardware_id': hardware_id
            }
        except Exception as e:
            print(f"获取设备信息失败: {e}")
            return {
                'device_fingerprint': 'default_fingerprint',
                'mac_address': '00:11:22:33:44:55',
                'hardware_id': 'default_hardware_id'
            }

    def _generate_encryption_key(self):
        key_material = f"{self.project_api_secret}{self.device_info['device_fingerprint']}{self.device_info['hardware_id']}"
        return hashlib.sha256(key_material.encode()).digest()

    def _encrypt_data(self, data):
        try:
            serialized_data = pickle.dumps(data)
            key = self.encryption_key
            encrypted_data = bytearray()
            for i, byte in enumerate(serialized_data):
                encrypted_data.append(byte ^ key[i % len(key)])
            return bytes(encrypted_data)
        except Exception as e:
            print(f"加密数据失败: {e}")
            return None

    def _decrypt_data(self, encrypted_data):
        try:
            key = self.encryption_key
            decrypted_data = bytearray()
            for i, byte in enumerate(encrypted_data):
                decrypted_data.append(byte ^ key[i % len(key)])
            data = pickle.loads(bytes(decrypted_data))
            return data
        except Exception as e:
            print(f"解密数据失败: {e}")
            return None

    def generate_signature(self, params):
        if 'signature' in params:
            del params['signature']
        sorted_params = sorted(params.items(), key=lambda x: x[0])
        str_to_sign = '&'.join([f"{key}={value}" for key, value in sorted_params])
        str_to_sign += f'&key={self.project_api_secret}'
        return hashlib.md5(str_to_sign.encode()).hexdigest()

    def _make_api_request(self, action, extra_params=None):
        params = {
            'action': action,
            'project_id': self.project_id,
            'timestamp': int(time.time()),
            'nonce': secrets.token_hex(8)
        }
        if extra_params:
            params.update(extra_params)
        params['signature'] = self.generate_signature(params.copy())
        try:
            response = requests.post(self.api_base, data=params, timeout=10)
            result = response.json()
            return result
        except requests.RequestException as e:
            return {'status': 'error', 'code': 'NETWORK_ERROR', 'message': f'网络请求失败: {str(e)}'}
        except json.JSONDecodeError:
            return {'status': 'error', 'code': 'JSON_ERROR', 'message': '响应格式错误'}
        except Exception as e:
            return {'status': 'error', 'code': 'UNKNOWN_ERROR', 'message': f'请求失败: {str(e)}'}

    def check_license(self, license_code):
        result = self._make_api_request('check', {'license': license_code})
        return result

    def deactivate_license(self, license_code=None):
        license_code = license_code or self.license_code
        if not license_code:
            return {'status': 'error', 'code': 'NO_LICENSE', 'message': '没有许可证'}
        result = self._make_api_request('deactivate', {
            'license': license_code,
            'device_fingerprint': self.device_info['device_fingerprint']
        })
        if result.get('status') == 'success':
            self.clear_cache()
        return result

    def renew_license(self, old_license, new_license):
        result = self._make_api_request('renew', {
            'license': old_license,
            'new_license': new_license,
            'device_fingerprint': self.device_info['device_fingerprint']
        })
        if result.get('status') == 'success':
            self.license_code = new_license
            self.save_cache()
        return result

    def activate_license(self, license_code):
        """激活许可证"""
        self.license_code = license_code

        print("\n" + "=" * 60)
        print("许可证激活流程开始")
        print("=" * 60)
        print(f"许可证代码: {license_code}")
        print(f"项目ID: {self.project_id}")
        print(f"API地址: {self.api_base}")

        # 设备信息详情
        device_info = {
            'mac_address': self.device_info['mac_address'],
            'hardware_id': self.device_info['hardware_id'],
            'os': platform.system(),
            'browser': 'LicenseValidator',
            'screen_resolution': '1920x1080',
            'cpu': platform.processor(),
            'ram': '16GB'
        }

        device_fingerprint = self.device_info['device_fingerprint']

        print("\n设备信息:")
        print(f"   - 设备指纹: {device_fingerprint}")
        print(f"   - MAC地址: {device_info['mac_address']}")
        print(f"   - 硬件ID: {device_info['hardware_id']}")
        print(f"   - 操作系统: {device_info['os']}")
        print(f"   - CPU: {device_info['cpu']}")

        # 准备请求参数
        request_params = {
            'license': license_code,
            'device_fingerprint': device_fingerprint,
            'device_info': json.dumps(device_info)
        }

        print("\nAPI请求参数:")
        print(f"   - action: activate")
        print(f"   - project_id: {self.project_id}")
        print(f"   - license: {license_code}")
        print(f"   - device_fingerprint: {device_fingerprint}")

        # 发送请求
        result = self._make_api_request('activate', request_params)

        print("\nAPI响应结果:")
        print(f"   原始响应: {json.dumps(result, indent=2, ensure_ascii=False)}")

        # 解析响应
        status = result.get('status', 'unknown')
        code = result.get('code', 'UNKNOWN')
        message = result.get('message', '无消息')
        data = result.get('data', {})

        print(f"\n响应解析:")
        print(f"   - 状态: {status}")
        print(f"   - 代码: {code}")
        print(f"   - 消息: {message}")
        print(f"   - 数据字段: {list(data.keys()) if data else '无'}")

        if result.get('status') == 'success':
            self.is_validated = True
            self.license_info = result
            self.is_vip = result.get('is_vip', False)
            # 解析自定义权限配置
            self.permissions = result.get('data', {}).get('permissions', {})

            print("\n激活成功!")
            print(f"   - 许可证已验证: {self.is_validated}")
            print(f"   - VIP状态: {self.is_vip}")

            if self.is_vip:
                self.vip_info = {
                    'level': result.get('vip_level', '尊贵VIP'),
                    'expiry': result.get('vip_expiry', '未知'),
                    'message': result.get('vip_message', ''),
                    'benefits': result.get('vip_benefits', {})
                }
                print("\nVIP信息:")
                print(f"   - 等级: {self.vip_info['level']}")
                print(f"   - 到期时间: {self.vip_info['expiry']}")
                print(f"   - 消息: {self.vip_info['message']}")
                if self.vip_info['benefits']:
                    print(f"   - 权益: {json.dumps(self.vip_info['benefits'], ensure_ascii=False)}")

            # 许可证详情
            license_data = result.get('data', {})
            # 支持 expires 和 expires_at 两种字段名
            expires_at = license_data.get('expires') or license_data.get('expires_at', '')
            duration_days = license_data.get('duration_days', 0)
            used_at = license_data.get('used_at', '')

            # 计算剩余天数和有效期天数
            remaining_days = '未知'
            total_days = duration_days
            if expires_at:
                try:
                    from datetime import datetime
                    expires_time = datetime.strptime(expires_at, "%Y-%m-%d %H:%M:%S")
                    diff = expires_time - datetime.now()
                    remaining_days = max(0, int(diff.total_seconds() / 86400))
                    # 如果有used_at，计算总有效期天数
                    if used_at:
                        used_time = datetime.strptime(used_at, "%Y-%m-%d %H:%M:%S")
                        total_days = (expires_time - used_time).days
                except:
                    pass
            elif used_at and duration_days > 0:
                try:
                    from datetime import datetime, timedelta
                    used_time = datetime.strptime(used_at, "%Y-%m-%d %H:%M:%S")
                    expires_time = used_time + timedelta(days=duration_days)
                    diff = expires_time - datetime.now()
                    remaining_days = max(0, int(diff.total_seconds() / 86400))
                except:
                    pass

            print("\n许可证详情:")
            print(f"   - 许可证类型: {license_data.get('license_type', '未知')}")
            print(f"   - 许可证名称: {license_data.get('license_name', '未知')}")
            print(f"   - 有效期天数: {total_days if total_days > 0 else (duration_days if duration_days > 0 else '未知')}")
            print(f"   - 到期时间: {expires_at or '未知'}")
            print(f"   - 剩余天数: {remaining_days}")
            print(f"   - 激活时间: {used_at or '未知'}")
            print(f"   - 状态: {license_data.get('status', '未知')}")

            # 保存缓存
            cache_result = self.save_cache()
            print(f"\n缓存保存: {'成功' if cache_result else '失败'}")

            print("\n" + "=" * 60)
            print("许可证激活流程完成")
            print("=" * 60 + "\n")

            return True, result
        else:
            error_msg = result.get('message', '未知错误')
            code = result.get('code', 'UNKNOWN')
            suggestion = result.get('suggestion', '')

            print("\n激活失败!")
            print(f"   - 错误代码: {code}")
            print(f"   - 错误消息: {error_msg}")
            if suggestion:
                print(f"   - 建议: {suggestion}")

            print("\n" + "=" * 60)
            print("许可证激活流程结束 (失败)")
            print("=" * 60 + "\n")

            return False, result

    def validate_license_online(self, license_code):
        device_fingerprint = self.device_info['device_fingerprint']
        result = self._make_api_request('validate', {
            'license': license_code,
            'device_fingerprint': device_fingerprint
        })
        if result.get('status') == 'success':
            self.license_info = result
            self.is_vip = result.get('is_vip', False)
            # 解析自定义权限配置
            self.permissions = result.get('data', {}).get('permissions', {})

            if self.is_vip:
                self.vip_info = {
                    'level': result.get('vip_level', '尊贵VIP'),
                    'expiry': result.get('vip_expiry', '未知'),
                    'message': result.get('vip_message', ''),
                    'benefits': result.get('vip_benefits', {})
                }

            self.save_cache()
            return True
        else:
            error_msg = result.get('message', '验证失败')
            code = result.get('code', 'UNKNOWN')
            print(f"❌ 许可证验证失败 [{code}]: {error_msg}")
            return False

    def heartbeat(self, license_code=None):
        """更新心跳，保持设备在线状态"""
        license_code = license_code or self.license_code
        if not license_code:
            return {'status': 'error', 'code': 'NO_LICENSE', 'message': '没有许可证'}
        result = self._make_api_request('heartbeat', {
            'license': license_code,
            'device_fingerprint': self.device_info['device_fingerprint']
        })
        return result

    def load_cache(self):
        if os.path.exists(self.cache_file):
            try:
                with open(self.cache_file, 'rb') as f:
                    encrypted_data = f.read()
                cache = self._decrypt_data(encrypted_data)
                if cache is None:
                    print("解密缓存失败")
                    self.clear_cache()
                    return False
                license_code = cache.get('license_code')
                license_info = cache.get('license_info', {})
                saved_at = cache.get('saved_at', '')
                if license_code:
                    print(f"✓ 找到缓存的许可证: {license_code}")
                    data = license_info.get('data', {})
                    # 支持 expires 和 expires_at 两种字段名
                    expires_str = data.get('expires') or data.get('expires_at', '')
                    remaining_days = data.get('remaining_days', 0)
                    is_expired = True
                    if expires_str:
                        try:
                            expires_time = datetime.strptime(expires_str, "%Y-%m-%d %H:%M:%S")
                            is_expired = expires_time < datetime.now()
                        except:
                            is_expired = remaining_days <= 0
                    if is_expired:
                        print("❌ 许可证已过期")
                        self.clear_cache()
                        return False
                    need_online_validation = True
                    if saved_at:
                        try:
                            saved_time = datetime.strptime(saved_at, "%Y-%m-%d %H:%M:%S")
                            hours_since_saved = (datetime.now() - saved_time).total_seconds() / 3600
                            if hours_since_saved < 24:
                                print("✓ 缓存验证有效，跳过在线验证")
                                need_online_validation = False
                            else:
                                print("🔄 缓存超过24小时，需要在线验证...")
                        except:
                            pass
                    if not need_online_validation:
                        self.license_code = license_code
                        self.license_info = license_info
                        self.is_validated = True
                        self.is_vip = license_info.get('is_vip', False)
                        return True
                    print("🔄 正在进行在线验证...")
                    validation_result = self.validate_license_online(license_code)
                    if validation_result:
                        self.license_code = license_code
                        self.is_validated = True
                        print("✓ 在线验证通过")
                        return True
                    else:
                        print("⚠️ 在线验证失败，但许可证未过期，使用缓存继续运行")
                        self.license_code = license_code
                        self.license_info = license_info
                        self.is_validated = True
                        self.is_vip = license_info.get('is_vip', False)
                        return True
                else:
                    print("⚠️ 缓存不完整")
            except Exception as e:
                print(f"加载缓存失败: {e}")
        return False

    def load_cache_no_check(self):
        if os.path.exists(self.cache_file):
            try:
                with open(self.cache_file, 'rb') as f:
                    encrypted_data = f.read()
                cache = self._decrypt_data(encrypted_data)
                if cache is None:
                    return False
                license_code = cache.get('license_code')
                license_info = cache.get('license_info', {})
                if license_code:
                    self.license_code = license_code
                    self.license_info = license_info
                    self.is_validated = True
                    self.is_vip = license_info.get('is_vip', False)
                    return True
            except Exception as e:
                print(f"加载缓存失败: {e}")
                return False
        return False

    def save_cache(self):
        try:
            cache_data = {
                'license_code': self.license_code,
                'license_info': self.license_info,
                'device_info': self.device_info,
                'project_id': self.project_id,
                'saved_at': datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            }
            encrypted_data = self._encrypt_data(cache_data)
            if encrypted_data is None:
                return False
            with open(self.cache_file, 'wb') as f:
                f.write(encrypted_data)
            json_data = {
                'license_code': self.license_code,
                'saved_at': datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            }
            try:
                with open(self.cache_file_json, 'w', encoding='utf-8') as f:
                    json.dump(json_data, f, ensure_ascii=False, indent=2)
                print(f"✓ 许可证已保存")
            except Exception as json_error:
                print(f"保存JSON缓存失败: {json_error}")
            return True
        except Exception as e:
            print(f"保存缓存失败: {e}")
            return False

    def clear_cache(self):
        try:
            if os.path.exists(self.cache_file):
                os.remove(self.cache_file)
            if os.path.exists(self.cache_file_json):
                os.remove(self.cache_file_json)
            return True
        except Exception as e:
            print(f"清除缓存失败: {e}")
            return False

    def get_license_info(self):
        """获取许可证信息"""
        if not self.is_validated:
            return None

        data = self.license_info.get('data', {})

        used_at_str = data.get('used_at', '')
        duration_days = data.get('duration_days', 0)
        # 支持 expires 和 expires_at 两种字段名
        expires_str = data.get('expires') or data.get('expires_at', '')
        remaining_days = 0
        is_expired = True

        # 如果 duration_days 为 0 但有 expires_at 和 used_at，计算 duration_days
        if duration_days == 0 and expires_str and used_at_str:
            try:
                expires_time = datetime.strptime(expires_str, "%Y-%m-%d %H:%M:%S")
                used_time = datetime.strptime(used_at_str, "%Y-%m-%d %H:%M:%S")
                calculated_days = (expires_time - used_time).days
                if calculated_days > 0:
                    duration_days = calculated_days
            except:
                pass

        if expires_str:
            try:
                expires_time = datetime.strptime(expires_str, "%Y-%m-%d %H:%M:%S")
                diff = expires_time - datetime.now()
                # 使用 ceil 向上取整，确保不足1天也算1天
                remaining_days = max(0, int(diff.total_seconds() / 86400))
                if diff.total_seconds() > 0 and remaining_days == 0:
                    remaining_days = 1
                is_expired = diff.total_seconds() <= 0
            except:
                is_expired = True
        elif used_at_str and duration_days > 0:
            try:
                used_time = datetime.strptime(used_at_str, "%Y-%m-%d %H:%M:%S")
                expires_time = used_time + timedelta(days=duration_days)
                diff = expires_time - datetime.now()
                # 使用 ceil 向上取整，确保不足1天也算1天
                remaining_days = max(0, int(diff.total_seconds() / 86400))
                if diff.total_seconds() > 0 and remaining_days == 0:
                    remaining_days = 1
                is_expired = diff.total_seconds() <= 0
            except:
                is_expired = True

        info = {
            'is_validated': self.is_validated,
            'is_vip': self.is_vip,
            'license_code': data.get('license_key', self.license_code),
            'expires': expires_str or '未知',
            'remaining_days': remaining_days,
            'license_type': data.get('license_type', '未知'),
            'license_name': data.get('license_name', ''),
            'duration_days': duration_days,
            'status': 'active' if not is_expired else 'expired',
            'app_name': self.app_name,
            'user_name': data.get('user_name', ''),
            'machine_code': self.device_info['device_fingerprint']
        }

        if self.is_vip:
            info['vip_info'] = self.vip_info

        return info

    # ========== 权限检查方法 ==========

    def check_feature(self, feature_name):
        """
        检查某个功能是否有权限
        
        :param feature_name: 功能名称，如 'export_excel', 'batch_import', 'api_access'
        :return: bool 是否有权限
        """
        features = self.permissions.get('features', {})
        return features.get(feature_name, False)

    def get_limit(self, limit_name, default=None):
        """
        获取某个限制值
        
        :param limit_name: 限制名称，如 'daily_queries', 'concurrent_users'
        :param default: 默认值（未设置时返回）
        :return: 限制值
        """
        limits = self.permissions.get('limits', {})
        return limits.get(limit_name, default)

    def get_max_projects(self):
        """获取最大项目管理数量"""
        return self.permissions.get('max_projects', 999)

    def get_max_servers(self):
        """获取最大服务器数量"""
        return self.permissions.get('max_servers', 999)

    def get_required_permissions(self):
        """获取完整权限配置字典"""
        return self.permissions


class ActivationDialog:
    """激活弹窗 - 蓝白灰清爽风格左右布局"""

    def __init__(self, validator, app_name):
        self.validator = validator
        self.app_name = app_name
        self.result = False
        self.root = None
        self.license_var = None
        self.purchase_url = "http://geo.com/admin/agent_manage.php"

    def show(self):
        """显示弹窗"""
        ctk.set_appearance_mode("light")
        ctk.set_default_color_theme("blue")
        self.root = ctk.CTk()
        self.root.title(f"{self.app_name}")
        self.root.resizable(False, False)
        self.root.protocol("WM_DELETE_WINDOW", self.on_exit)
        self.window_width = 750
        self.window_height = 460
        try:
            icon_path = os.path.join(os.path.dirname(__file__), 'ico', 'su.png')
            if os.path.exists(icon_path):
                self.root.iconphoto(True, tk.PhotoImage(file=icon_path))
        except:
            pass
        self.create_widgets()
        self.root.update_idletasks()
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()
        x = (screen_width // 2) - (self.window_width // 2)
        y = (screen_height // 2) - (self.window_height // 2)
        self.root.geometry(f"{self.window_width}x{self.window_height}+{x}+{y}")
        self.root.mainloop()
        return self.result

    def create_widgets(self):
        """创建蓝白灰清爽风格左右布局界面"""
        # 主容器
        main_frame = ctk.CTkFrame(self.root, fg_color="#F8FAFE", corner_radius=0)
        main_frame.pack(fill="both", expand=True, padx=0, pady=0)
        
        # 左侧面板 - 蓝色品牌区
        left_frame = ctk.CTkFrame(main_frame, fg_color="#2563EB", corner_radius=0, width=300)
        left_frame.pack(side="left", fill="both", expand=False, padx=0, pady=0)
        left_frame.pack_propagate(False)
        
        # 左侧内容容器
        left_content = ctk.CTkFrame(left_frame, fg_color="transparent")
        left_content.pack(expand=True, fill="both", padx=30, pady=30)
        
        # 品牌徽章
        badge_frame = ctk.CTkFrame(left_content, fg_color="#FFFFFF", corner_radius=20, height=36)
        badge_frame.pack(pady=(0, 20))
        badge_frame.pack_propagate(False)
        ctk.CTkLabel(badge_frame, text="PREMIUM", font=("Microsoft YaHei", 12, "bold"),
                    text_color="#2563EB").pack(expand=True)
        
        # Logo图标
        logo_frame = ctk.CTkFrame(left_content, fg_color="transparent", corner_radius=0)
        logo_frame.pack(pady=(0, 15))
        try:
            from PIL import Image, ImageTk
            logo_path = os.path.join(os.path.dirname(__file__), 'ico', 'su.png')
            if os.path.exists(logo_path):
                logo_image = Image.open(logo_path)
                logo_image = logo_image.resize((80, 80), Image.Resampling.LANCZOS)
                logo_tk = ImageTk.PhotoImage(logo_image)
                logo_label = tk.Label(logo_frame, image=logo_tk, bg="#2563EB")
                logo_label.pack()
                logo_label.image = logo_tk
            else:
                ctk.CTkLabel(logo_frame, text="Lock", font=("Microsoft YaHei", 40),
                            text_color="#FFFFFF").pack()
        except:
            ctk.CTkLabel(logo_frame, text="Lock", font=("Microsoft YaHei", 40),
                        text_color="#FFFFFF").pack()
        
        # 软件名称
        ctk.CTkLabel(left_content, text=self.app_name, font=("Microsoft YaHei", 16, "bold"),
                    text_color="#FFFFFF", justify="center").pack(pady=(0, 8))
        
        # 副标题
        ctk.CTkLabel(left_content, text="软件授权激活", font=("Microsoft YaHei", 13),
                    text_color="#BFDBFE").pack(pady=(0, 25))
        
        # 装饰线
        separator_frame = ctk.CTkFrame(left_content, fg_color="#93C5FD", corner_radius=1, height=2)
        separator_frame.pack(fill="x", pady=(0, 25), ipady=1)
        
        # 设备信息卡片
        device_card = ctk.CTkFrame(left_content, fg_color="#1E40AF", corner_radius=10,
                                  border_color="#60A5FA", border_width=1)
        device_card.pack(fill="x", pady=(0, 20))
        device_inner = ctk.CTkFrame(device_card, fg_color="transparent")
        device_inner.pack(fill="x", padx=15, pady=15)
        ctk.CTkLabel(device_inner, text="设备信息", font=("Microsoft YaHei", 12, "bold"),
                    text_color="#93C5FD", justify="left").pack(anchor="w", pady=(0, 10))
        device_info = self.validator.device_info
        device_text = f"设备ID: {device_info['device_fingerprint'][:16]}...\n"
        device_text += f"硬件码: {device_info['hardware_id'][:16]}..."
        ctk.CTkLabel(device_inner, text=device_text, font=("Microsoft YaHei", 10),
                    text_color="#DBEAFE", justify="left").pack(anchor="w")
        
        # 底部购买提示
        bottom_frame = ctk.CTkFrame(left_content, fg_color="transparent")
        bottom_frame.pack(side="bottom", fill="x", pady=(0, 10))
        ctk.CTkLabel(bottom_frame, text="还没有许可证？", font=("Microsoft YaHei", 11),
                    text_color="#93C5FD").pack(pady=(0, 10))
        purchase_btn = ctk.CTkButton(bottom_frame, text="立即购买卡密", font=("Microsoft YaHei", 12, "bold"),
                                     fg_color="transparent", hover_color="#1D4ED8",
                                     text_color="#FFFFFF", corner_radius=8, height=36,
                                     border_color="#FFFFFF", border_width=1,
                                     command=self.on_buy_click)
        purchase_btn.pack(fill="x")
        
        # 右侧面板 - 激活表单
        right_frame = ctk.CTkFrame(main_frame, fg_color="#FFFFFF", corner_radius=0)
        right_frame.pack(side="left", fill="both", expand=True, padx=0, pady=0)
        
        # 右侧内容容器
        right_content = ctk.CTkFrame(right_frame, fg_color="transparent")
        right_content.pack(expand=True, fill="both", padx=50, pady=40)
        
        # 激活标题
        title_frame = ctk.CTkFrame(right_content, fg_color="transparent")
        title_frame.pack(fill="x", pady=(0, 10))
        ctk.CTkLabel(title_frame, text="激活软件授权", 
                    font=("Microsoft YaHei", 20, "bold"),
                    text_color="#1E3A5F").pack(anchor="w")
        ctk.CTkLabel(right_content, text="请输入您的许可证密钥以激活并解锁全部功能", 
                    font=("Microsoft YaHei", 12),
                    text_color="#6B7280").pack(anchor="w", pady=(0, 30))
        
        # 密钥输入框
        input_card = ctk.CTkFrame(right_content, fg_color="#F8FAFE", corner_radius=12,
                                 border_color="#E5E7EB", border_width=1)
        input_card.pack(fill="x", pady=(0, 25))
        input_inner = ctk.CTkFrame(input_card, fg_color="transparent")
        input_inner.pack(fill="x", padx=25, pady=25)
        ctk.CTkLabel(input_inner, text="许可证密钥", font=("Microsoft YaHei", 12, "bold"),
                    text_color="#1E3A5F", justify="left").pack(anchor="w", pady=(0, 12))
        self.license_var = tk.StringVar()
        license_entry = ctk.CTkEntry(input_inner, textvariable=self.license_var,
                                     font=("Microsoft YaHei", 13),
                                     fg_color="#FFFFFF", text_color="#1F2937",
                                     border_color="#D1D5DB", border_width=1,
                                     corner_radius=8, height=48,
                                     placeholder_text="请输入您的许可证密钥...")
        license_entry.pack(fill="x", ipady=5)
        
        # 按钮区域
        button_frame = ctk.CTkFrame(right_content, fg_color="transparent")
        button_frame.pack(fill="x", side="bottom")
        
        # 激活按钮 - 蓝色主色调
        self.activate_btn = ctk.CTkButton(button_frame, text="立即激活授权",
                                          font=("Microsoft YaHei", 14, "bold"),
                                          fg_color="#2563EB", hover_color="#1D4ED8",
                                          text_color="#FFFFFF", corner_radius=10,
                                          height=50, command=self.on_activate)
        self.activate_btn.pack(fill="x", pady=(0, 12))
        
        # 退出按钮
        exit_btn = ctk.CTkButton(button_frame, text="暂不激活，退出软件",
                                 font=("Microsoft YaHei", 11),
                                 fg_color="transparent", hover_color="#F3F4F6",
                                 text_color="#9CA3AF", border_color="#E5E7EB",
                                 border_width=1, corner_radius=10,
                                 height=42, command=self.on_exit)
        exit_btn.pack(fill="x")
        
        # 绑定快捷键
        self.root.bind('<Return>', lambda event: self.on_activate())
        self.root.bind('<Escape>', lambda event: self.on_exit())
        self.root.after(100, license_entry.focus)

    def on_buy_click(self):
        """购买按钮点击"""
        try:
            webbrowser.open(self.purchase_url)
            tk.messagebox.showinfo("购买卡密", "已打开购买页面，请购买后返回输入卡密激活。")
        except Exception as e:
            tk.messagebox.showerror("错误", f"无法打开浏览器：{str(e)}")

    def on_activate(self):
        """激活按钮点击"""
        license_code = self.license_var.get().strip() if self.license_var else ""
        if not license_code:
            tk.messagebox.showerror("错误", "许可证密钥不能为空！")
            return
        self.activate_btn.configure(state="disabled", text="激活中...")
        self.root.update()
        success, result = self.validator.activate_license(license_code)
        self.activate_btn.configure(state="normal", text="立即激活授权")
        if success:
            tk.messagebox.showinfo("激活成功", "许可证激活成功！\n软件即将启动。")
            self.result = True
            self.root.quit()
            self.root.destroy()
        else:
            error_msg = result.get('message', '未知错误')
            code = result.get('code', 'UNKNOWN')
            suggestion = result.get('suggestion', '')
            full_message = f"[{code}] {error_msg}"
            if suggestion:
                full_message += f"\n\n建议: {suggestion}"
            retry = tk.messagebox.askretrycancel("激活失败", full_message)
            if not retry:
                self.on_exit()

    def on_exit(self):
        """退出"""
        self.result = False
        self.root.quit()
        self.root.destroy()


def require_license(project_id, project_api_secret, app_name="软件名称", cache_suffix=""):
    """许可证验证装饰器"""
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            validator = LicenseValidator(project_id, project_api_secret, app_name, cache_suffix)
            has_cache = validator.load_cache_no_check()
            if has_cache:
                license_info = validator.get_license_info()
                if license_info and license_info.get('status') == 'active':
                    print("许可证有效，直接运行")
                    return func(validator, *args, **kwargs)
                else:
                    print("许可证已过期，需要续期")
                    dialog = ActivationDialog(validator, app_name)
                    if dialog.show():
                        print("许可证续期成功")
                        return func(validator, *args, **kwargs)
                    else:
                        print("用户取消续期")
                        sys.exit(0)
            else:
                print("首次使用，需要激活许可证")
                dialog = ActivationDialog(validator, app_name)
                if dialog.show():
                    print("许可证激活成功")
                    return func(validator, *args, **kwargs)
                else:
                    print("用户取消激活")
                    sys.exit(0)
        return wrapper
    return decorator


def license_manager(project_id, project_api_secret, app_name="软件名称", cache_suffix=""):
    """许可证管理器工厂函数"""
    validator = LicenseValidator(project_id, project_api_secret, app_name, cache_suffix)
    class LicenseManager:
        def check_license(self):
            if validator.load_cache():
                return True
            else:
                dialog = ActivationDialog(validator, app_name)
                return dialog.show()
        def get_validator(self):
            return validator
        def get_license_info(self):
            return validator.get_license_info()
        def clear_cache(self):
            return validator.clear_cache()
        def check_license_status(self, license_code):
            return validator.check_license(license_code)
        def deactivate(self):
            return validator.deactivate_license()
        def renew(self, old_license, new_license):
            return validator.renew_license(old_license, new_license)
    return LicenseManager()


if __name__ == "__main__":
    @require_license(
        project_id="1001",
        project_api_secret="f2113e6c61b86a7c61a74c3756b684fa",
        app_name="示例软件"
    )
    def my_software(validator):
        print("\n" + "=" * 60)
        print("软件启动成功!")
        print("=" * 60)
        license_info = validator.get_license_info()
        if license_info:
            print(f"许可证代码: {license_info['license_code']}")
            print(f"许可证类型: {license_info['license_type']}")
            print(f"状态: {license_info['status']}")
            print(f"剩余天数: {license_info['remaining_days']}")
        print("\n可用功能:")
        print("1. 检查卡密状态 - validator.check_license()")
        print("2. 解绑设备 - validator.deactivate_license()")
        print("3. 续期许可证 - validator.renew_license()")

    print("=" * 60)
    print("许可证装饰器示例")
    print("=" * 60)
    try:
        my_software()
    except SystemExit:
        print("软件因许可证验证失败而退出")
        os._exit(0)
    except Exception as e:
        print(f"软件运行出错: {e}")
