import os
import sys
import json
import time
import hashlib
import random
import subprocess
import platform
from datetime import datetime

try:
    import requests
except ImportError:
    print("正在安装必要的依赖库...")
    try:
        subprocess.check_call([sys.executable, "-m", "pip", "install", "requests"])
        import requests
    except Exception:
        print("依赖库安装失败，请手动执行: pip install requests")
        sys.exit(1)

APP_IDENTIFIER = "应用标识常量"
APP_SECURITY_KEY = "应用KEY"
ENCRYPTION_ENABLED = True
ENCRYPTION_SECRET_KEY = "加密KEY"
CURRENT_SOFTWARE_VERSION = "1.0"
LICENSE_STORAGE_PATH = "/sdcard/Android/license.key"
DEVICE_IDENTIFIER_PATH = "/storage/emulated/0/Android/device.id"
SYSTEM_DEVICE_ID = 0

def get_real_device_id():
    """获取真实的设备标识符
    原理：通过多种系统级方法获取设备唯一标识，确保每个设备都有唯一的设备码
    运行流程：
    1. 尝试获取Android设备的序列号（Serial Number）
    2. 尝试获取设备MAC地址作为备选
    3. 尝试读取设备的CPU信息组合
    4. 使用硬件信息组合生成设备指纹
    5. 如果以上方法都失败，无法获取设备码，则无法继续使用
    """
    device_id = ""
    
    # 方法1: 尝试获取Android设备的序列号（最可靠的设备标识）
    try:
        # 通过读取Android系统属性获取序列号
        serial_no = subprocess.check_output(['getprop', 'ro.serialno'], stderr=subprocess.DEVNULL).decode('utf-8').strip()
        if serial_no and len(serial_no) > 5 and serial_no != "unknown":
            print(f"成功获取设备序列号: {serial_no}")
            # 使用序列号的MD5哈希值作为设备标识
            device_id = hashlib.md5(serial_no.encode()).hexdigest()[:12]
            return int(device_id, 16) % 1000000
    except:
        pass
    
    # 方法2: 尝试获取设备的MAC地址
    try:
        # 读取无线网络接口的MAC地址
        mac_path = "/sys/class/net/wlan0/address"
        if os.path.exists(mac_path):
            with open(mac_path, 'r') as f:
                mac_address = f.read().strip()
                if mac_address:
                    print(f"成功获取设备MAC地址: {mac_address}")
                    # 移除冒号，取MD5哈希值作为设备标识
                    mac_clean = mac_address.replace(':', '')
                    device_id = hashlib.md5(mac_clean.encode()).hexdigest()[:12]
                    return int(device_id, 16) % 1000000
    except:
        pass
    
    # 方法3: 尝试获取Android设备ID
    try:
        # 通过Android系统属性获取设备ID
        device_id_prop = subprocess.check_output(['getprop', 'ro.boot.serialno'], stderr=subprocess.DEVNULL).decode('utf-8').strip()
        if device_id_prop and len(device_id_prop) > 5 and device_id_prop != "unknown":
            print(f"成功获取设备ID: {device_id_prop}")
            device_id = hashlib.md5(device_id_prop.encode()).hexdigest()[:12]
            return int(device_id, 16) % 1000000
    except:
        pass
    
    # 方法4: 尝试读取CPU信息组合作为设备指纹
    try:
        # 读取CPU信息文件
        cpu_info_path = "/proc/cpuinfo"
        if os.path.exists(cpu_info_path):
            with open(cpu_info_path, 'r') as f:
                cpu_info = f.read()
                # 提取CPU相关标识信息
                cpu_identifiers = []
                
                # 查找Serial字段（某些ARM处理器有）
                import re
                serial_match = re.search(r'Serial\s*:\s*([0-9a-fA-F]+)', cpu_info)
                if serial_match:
                    cpu_identifiers.append(serial_match.group(1))
                
                # 查找Hardware字段
                hardware_match = re.search(r'Hardware\s*:\s*(\S+)', cpu_info)
                if hardware_match:
                    cpu_identifiers.append(hardware_match.group(1))
                
                # 查找Revision字段
                revision_match = re.search(r'Revision\s*:\s*(\S+)', cpu_info)
                if revision_match:
                    cpu_identifiers.append(revision_match.group(1))
                
                if cpu_identifiers:
                    cpu_fingerprint = ''.join(cpu_identifiers)
                    print(f"成功获取CPU指纹: {cpu_fingerprint}")
                    device_id = hashlib.md5(cpu_fingerprint.encode()).hexdigest()[:12]
                    return int(device_id, 16) % 1000000
    except:
        pass
    
    # 方法5: 尝试获取Android ID（Android系统提供的唯一标识）
    try:
        # Android ID存储在系统文件中
        android_id_path = "/data/data/com.android.providers.settings/databases/settings.db"
        if os.path.exists(android_id_path):
            # 注意：实际读取需要root权限
            print("检测到Android ID文件，需要root权限读取")
    except:
        pass
    
    # 所有方法都失败，无法获取设备码
    print("错误：无法获取设备唯一标识")
    print("可能的原因：")
    print("1. 设备权限不足")
    print("2. 设备信息被隐藏")
    print("3. 系统限制访问设备信息")
    return None  # 返回None表示获取失败

def initialize_device_identity():
    """初始化设备身份标识
    原理：从文件读取已有设备码或获取新的设备码并保存到文件
    运行流程：
    1. 检查设备标识文件是否存在且非空
    2. 如果文件存在，读取文件中的设备码
    3. 如果文件不存在，调用get_real_device_id获取真实设备码
    4. 将获取的设备码保存到文件
    5. 如果无法获取设备码，程序无法继续运行
    """
    global SYSTEM_DEVICE_ID
    device_code = 0
    
    try:
        # 首先尝试从文件读取设备码
        if os.path.exists(DEVICE_IDENTIFIER_PATH) and os.path.getsize(DEVICE_IDENTIFIER_PATH) > 0:
            with open(DEVICE_IDENTIFIER_PATH, 'r') as file:
                content = file.read().strip()
                if content:
                    device_code = int(content)
                    print(f"从文件加载设备码: {device_code}")
                    SYSTEM_DEVICE_ID = device_code
                    return 0  # 成功从文件读取
        else:
            print("设备标识文件不存在，开始获取真实设备码...")
            
    except Exception as e:
        print(f"读取设备码文件异常: {str(e)}")
    
    # 文件不存在或读取失败，获取真实设备码
    device_code = get_real_device_id()
    
    if device_code is None:
        # 无法获取设备码，程序无法继续运行
        print("致命错误：无法获取设备唯一标识，程序无法继续运行")
        print("请检查设备权限或联系技术支持")
        sys.exit(1)  # 直接退出程序
    
    print(f"成功获取设备码: {device_code}")
    
    # 保存到文件
    try:
        # 确保目录存在
        os.makedirs(os.path.dirname(DEVICE_IDENTIFIER_PATH), exist_ok=True)
        with open(DEVICE_IDENTIFIER_PATH, 'w') as file:
            file.write(str(device_code))
        print("设备码已保存到文件")
    except Exception as e:
        print(f"设备码保存失败: {str(e)}")
        # 即使保存失败，仍然使用内存中的设备码
    
    SYSTEM_DEVICE_ID = device_code
    return 0  # 成功获取并设置设备码

def compute_md5_signature(license_key, device_id, app_key):
    """计算MD5签名
    原理：将请求参数按固定格式拼接后计算MD5哈希值，防止请求被篡改
    运行流程：
    1. 获取当前Unix时间戳
    2. 按固定格式拼接字符串：kami=卡密&markcode=设备标识码&t=时间戳&应用密钥
    3. 使用MD5算法计算字符串哈希值
    4. 返回十六进制格式的哈希值
    """
    current_timestamp = int(time.time())
    signature_string = f"kami={license_key}&markcode={device_id}&t={current_timestamp}&{app_key}"
    return hashlib.md5(signature_string.encode('utf-8')).hexdigest()

def perform_rc4_cryptography(data_input, crypt_key, is_encrypt_mode):
    """执行RC4加密/解密
    原理：RC4流密码算法，通过密钥调度和伪随机生成实现对称加密
    运行流程：
    1. 初始化S盒（256个字节的排列）
    2. 使用密钥调度算法（KSA）打乱S盒
    3. 使用伪随机生成算法（PRGA）生成密钥流
    4. 将数据与密钥流进行异或操作
    5. 加密返回十六进制字符串，解密返回UTF-8字符串
    """
    try:
        S_box = list(range(256))
        key_index = 0
        key_bytes = crypt_key.encode('utf-8')
        
        # 密钥调度算法（KSA）
        for i in range(256):
            key_index = (key_index + S_box[i] + key_bytes[i % len(key_bytes)]) % 256
            S_box[i], S_box[key_index] = S_box[key_index], S_box[i]
        
        i = j = 0
        result_data = bytearray()
        
        # 根据模式准备输入数据
        if is_encrypt_mode:
            input_bytes = data_input.encode('utf-8')
        else:
            try:
                input_bytes = bytes.fromhex(data_input)
            except ValueError:
                return None
        
        # 伪随机生成算法（PRGA）和加密/解密
        for byte_character in input_bytes:
            i = (i + 1) % 256
            j = (j + S_box[i]) % 256
            S_box[i], S_box[j] = S_box[j], S_box[i]
            # 生成密钥流字节并与数据字节异或
            result_data.append(byte_character ^ S_box[(S_box[i] + S_box[j]) % 256])
        
        # 根据模式返回相应格式的数据
        if is_encrypt_mode:
            return bytes(result_data).hex()
        else:
            return bytes(result_data).decode('utf-8', errors='ignore')
    except Exception:
        return None

def convert_unix_timestamp(timestamp_value):
    """转换Unix时间戳为可读格式
    原理：将Unix时间戳转换为本地时间的字符串表示
    运行流程：
    1. 将输入转换为整数类型的时间戳
    2. 使用datetime.fromtimestamp转换为datetime对象
    3. 格式化日期时间字符串
    """
    try:
        if isinstance(timestamp_value, str):
            timestamp_value = int(timestamp_value)
        date_object = datetime.fromtimestamp(timestamp_value)
        return date_object.strftime("%Y-%m-%d %H:%M:%S")
    except:
        return "时间格式异常"

def retrieve_system_announcement_function():
    """获取系统公告
    原理：向服务器请求公告信息，解密并显示
    运行流程：
    1. 构建公告请求URL
    2. 发送HTTP GET请求
    3. 检查响应状态码
    4. 根据加密设置解密响应
    5. 解析JSON数据并提取公告内容
    """
    try:
        announcement_url = f"http://haraichi.top/api.php?api=notice&app={APP_IDENTIFIER}"
        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'}
        server_response = requests.get(url=announcement_url, timeout=15, headers=headers)
        
        if server_response.status_code != 200:
            return
        
        response_text = server_response.text.strip()
        if not response_text:
            return
        
        if ENCRYPTION_ENABLED:
            decrypted_content = perform_rc4_cryptography(response_text, ENCRYPTION_SECRET_KEY, False)
            if decrypted_content is None:
                try:
                    announcement_data = json.loads(response_text)
                except json.JSONDecodeError:
                    return
            else:
                try:
                    announcement_data = json.loads(decrypted_content)
                except json.JSONDecodeError:
                    return
        else:
            try:
                announcement_data = json.loads(response_text)
            except json.JSONDecodeError:
                return
        
        response_code = announcement_data.get('code')
        if response_code is None:
            return
        
        if response_code == 200:
            announcement_content = announcement_data.get('msg', {}).get('app_gg')
            if announcement_content:
                print(f"公告:{announcement_content}")
            else:
                print("无公告内容")
            
    except:
        pass

def verify_authorization_key_function():
    """验证授权密钥
    原理：验证用户输入的授权密钥是否有效
    运行流程：
    1. 获取用户输入的授权密钥
    2. 生成时间戳和签名
    3. 构建请求数据
    4. 根据加密设置加密请求数据
    5. 发送验证请求到服务器
    6. 解析服务器响应
    7. 验证成功则保存授权信息
    """
    try:
        license_input = input("\n请输入授权密钥: ").strip()
        if not license_input:
            print("输入读取失败")
            return 1
    except KeyboardInterrupt:
        print("\n操作已取消")
        return 1
    
    try:
        current_time = time.time()
        timestamp_value = int(current_time)

        # 生成请求签名
        signature_string = f"kami={license_input}&markcode={SYSTEM_DEVICE_ID}&t={timestamp_value}&{APP_SECURITY_KEY}"
        digital_signature = hashlib.md5(signature_string.encode('utf-8')).hexdigest()

        # 构建请求数据
        request_data = f"kami={license_input}&markcode={SYSTEM_DEVICE_ID}&t={timestamp_value}&sign={digital_signature}"
        
        # 根据加密设置处理请求数据
        if ENCRYPTION_ENABLED:
            encrypted_data = perform_rc4_cryptography(request_data, ENCRYPTION_SECRET_KEY, True)
            if encrypted_data is None:
                print("数据加密失败")
                return 1
            final_payload = f"data={encrypted_data}"
        else:
            final_payload = request_data
        
        # 构建请求URL
        request_url = f"http://haraichi.top/api.php?api=kmlogon&app={APP_IDENTIFIER}&{final_payload}&value={random.randint(0,999999)}"
        
        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'}
        server_response = requests.get(url=request_url, timeout=15, headers=headers)
        
        if server_response.status_code != 200:
            print("服务器响应异常")
            return 1
        
        response_text = server_response.text.strip()
        if not response_text:
            print("服务器返回空响应")
            return 1
        
        # 解密并解析响应
        if ENCRYPTION_ENABLED:
            decrypted_response = perform_rc4_cryptography(response_text, ENCRYPTION_SECRET_KEY, False)
            if decrypted_response is None:
                try:
                    response_json = json.loads(response_text)
                except json.JSONDecodeError:
                    print("响应解析失败")
                    return 1
            else:
                try:
                    response_json = json.loads(decrypted_response)
                except json.JSONDecodeError:
                    print("响应解析失败")
                    return 1
        else:
            try:
                response_json = json.loads(response_text)
            except json.JSONDecodeError:
                print("响应解析失败")
                return 1
        
        response_code = response_json.get('code', 0)
        
        if response_code == 200:
            message_field = response_json.get('msg', {})
            license_info = message_field.get('kami', license_input)
            expiration_info = message_field.get('vip', '0')
            
            print(f"授权密钥{license_info}验证成功，有效期至:{convert_unix_timestamp(expiration_info)}")
            
            # 保存授权信息到文件
            try:
                os.system("mkdir -p /sdcard/Android/")
                with open(LICENSE_STORAGE_PATH, 'w') as file_pointer:
                    file_pointer.write(license_input)
                print("授权信息已保存")
            except:
                print("授权信息保存失败")
            
            return 200
        else:
            error_msg = response_json.get('msg', '未知错误')
            print(f"授权密钥验证失败: {error_msg}")
            return 1
            
    except requests.exceptions.Timeout:
        print("服务器请求失败")
        return 1
    except:
        print("响应解析异常")
        return 1

def unbind_authorization_function():
    """解绑授权密钥
    原理：将授权密钥从当前设备解绑，允许在其他设备使用
    运行流程：
    1. 获取用户输入的授权密钥
    2. 生成时间戳和签名
    3. 构建解绑请求
    4. 发送解绑请求到服务器
    5. 解析服务器响应
    """
    try:
        license_input = input("\n请输入需要解绑的授权密钥: ").strip()
        if not license_input:
            print("输入读取失败")
            return 1
    except KeyboardInterrupt:
        print("\n操作已取消")
        return 1
    
    try:
        current_time = time.time()
        timestamp_value = int(current_time)

        # 生成请求签名
        signature_string = f"kami={license_input}&markcode={SYSTEM_DEVICE_ID}&t={timestamp_value}&{APP_SECURITY_KEY}"
        digital_signature = hashlib.md5(signature_string.encode('utf-8')).hexdigest()

        # 构建请求数据
        request_data = f"kami={license_input}&markcode={SYSTEM_DEVICE_ID}&t={timestamp_value}&sign={digital_signature}"
        
        # 根据加密设置处理请求数据
        if ENCRYPTION_ENABLED:
            encrypted_data = perform_rc4_cryptography(request_data, ENCRYPTION_SECRET_KEY, True)
            if encrypted_data is None:
                print("数据加密失败")
                return 1
            final_payload = f"data={encrypted_data}"
        else:
            final_payload = request_data
        
        # 构建解绑请求URL
        request_url = f"http://haraichi.top/api.php?api=kmunmachine&app={APP_IDENTIFIER}&{final_payload}&value={random.randint(0,999999)}"
        
        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'}
        server_response = requests.get(url=request_url, timeout=15, headers=headers)
        
        if server_response.status_code != 200:
            print("服务器响应异常")
            return 1
        
        response_text = server_response.text.strip()
        if not response_text:
            print("服务器返回空响应")
            return 1
        
        # 解密并解析响应
        if ENCRYPTION_ENABLED:
            decrypted_response = perform_rc4_cryptography(response_text, ENCRYPTION_SECRET_KEY, False)
            if decrypted_response is None:
                try:
                    response_json = json.loads(response_text)
                except json.JSONDecodeError:
                    print("响应解析失败")
                    return 1
            else:
                try:
                    response_json = json.loads(decrypted_response)
                except json.JSONDecodeError:
                    print("响应解析失败")
                    return 1
        else:
            try:
                response_json = json.loads(response_text)
            except json.JSONDecodeError:
                print("响应解析失败")
                return 1
        
        response_code = response_json.get('code', 0)
        
        if response_code == 200:
            print(f"授权密钥{license_input}解绑成功")
            return 200
        elif response_code == 201:
            message_content = response_json.get('msg', '解绑操作失败')
            print(f"{message_content}")
            return 1
        else:
            error_msg = response_json.get('msg', '解绑失败')
            print(f"{error_msg}")
            return 1
            
    except requests.exceptions.Timeout:
        print("服务器请求失败")
        return 1
    except:
        print("响应解析异常")
        return 1

def check_version_information_function():
    """检查版本信息
    原理：向服务器查询最新版本信息，检查是否需要更新
    运行流程：
    1. 构建版本检查请求URL
    2. 发送HTTP GET请求
    3. 解密并解析响应
    4. 比较当前版本和最新版本
    5. 根据检查结果返回不同状态码
    """
    try:
        request_url = f"http://haraichi.top/api.php?api=ini&app={APP_IDENTIFIER}"
        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'}
        server_response = requests.get(url=request_url, timeout=15, headers=headers)
        
        if server_response.status_code != 200:
            print("版本信息获取失败")
            return 0
        
        response_text = server_response.text.strip()
        if not response_text:
            print("版本信息获取失败")
            return 0
        
        # 解密并解析响应
        if ENCRYPTION_ENABLED:
            decrypted_response = perform_rc4_cryptography(response_text, ENCRYPTION_SECRET_KEY, False)
            if decrypted_response is None:
                try:
                    response_json = json.loads(response_text)
                except json.JSONDecodeError:
                    print("版本信息解析异常")
                    return 0
            else:
                try:
                    response_json = json.loads(decrypted_response)
                except json.JSONDecodeError:
                    print("版本信息解析异常")
                    return 0
        else:
            try:
                response_json = json.loads(response_text)
            except json.JSONDecodeError:
                print("版本信息解析异常")
                return 0
        
        response_code = response_json.get('code', 0)
        
        if response_code == 200:
            message_field = response_json.get('msg', {})
            version_info = message_field.get('version', CURRENT_SOFTWARE_VERSION)
            version_description = message_field.get('version_info', '')
            update_notice = message_field.get('app_update_show', '')
            
            print(f"当前版本:{CURRENT_SOFTWARE_VERSION}")
            print(f"最新版本:{version_info}")
            
            if version_description:
                print(f"版本描述:{version_description}")
            
            if update_notice:
                print(f"更新公告:{update_notice}")
            
            if CURRENT_SOFTWARE_VERSION != version_info:
                update_url = message_field.get('app_update_url', '')
                mandatory_update = message_field.get('app_update_must', 'n')
                
                if update_url:
                    print(f"更新链接: {update_url}")
                
                if mandatory_update == 'y':
                    print("检测到强制更新要求")
                    return 1
                else:
                    print("检测到可用更新")
                    return 2
            else:
                print("当前为最新版本")
                return 0
        else:
            print("版本信息检查失败")
            return 0
            
    except requests.exceptions.Timeout:
        print("版本信息获取失败")
        return 0
    except:
        print("版本信息解析异常")
        return 0

def auto_login_function():
    """自动登录功能
    原理：尝试使用本地保存的授权密钥自动登录
    运行流程：
    1. 检查授权文件是否存在
    2. 读取本地保存的授权密钥
    3. 向服务器验证该密钥
    4. 验证成功则自动登录
    """
    try:
        if not os.path.exists(LICENSE_STORAGE_PATH):
            return False
            
        with open(LICENSE_STORAGE_PATH, 'r') as file:
            license_input = file.read().strip()
            
        if not license_input:
            return False
        
        # 构建验证请求
        current_time = time.time()
        timestamp_value = int(current_time)

        signature_string = f"kami={license_input}&markcode={SYSTEM_DEVICE_ID}&t={timestamp_value}&{APP_SECURITY_KEY}"
        digital_signature = hashlib.md5(signature_string.encode('utf-8')).hexdigest()

        request_data = f"kami={license_input}&markcode={SYSTEM_DEVICE_ID}&t={timestamp_value}&sign={digital_signature}"
        
        if ENCRYPTION_ENABLED:
            encrypted_data = perform_rc4_cryptography(request_data, ENCRYPTION_SECRET_KEY, True)
            if encrypted_data is None:
                return False
            final_payload = f"data={encrypted_data}"
        else:
            final_payload = request_data
        
        request_url = f"http://haraichi.top/api.php?api=kmlogon&app={APP_IDENTIFIER}&{final_payload}&value={random.randint(0,999999)}"
        
        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'}
        server_response = requests.get(url=request_url, timeout=10, headers=headers)
        
        if server_response.status_code != 200:
            return False
        
        response_text = server_response.text.strip()
        if not response_text:
            return False
        
        # 解密并解析响应
        if ENCRYPTION_ENABLED:
            decrypted_response = perform_rc4_cryptography(response_text, ENCRYPTION_SECRET_KEY, False)
            if decrypted_response is None:
                try:
                    response_json = json.loads(response_text)
                except json.JSONDecodeError:
                    return False
            else:
                try:
                    response_json = json.loads(decrypted_response)
                except json.JSONDecodeError:
                    return False
        else:
            try:
                response_json = json.loads(response_text)
            except json.JSONDecodeError:
                return False
        
        response_code = response_json.get('code', 0)
        
        if response_code == 200:
            message_field = response_json.get('msg', {})
            license_info = message_field.get('kami', license_input)
            expiration_info = message_field.get('vip', '0')
            
            print(f"自动登录成功")
            print(f"授权密钥{license_info}验证成功，有效期至:{convert_unix_timestamp(expiration_info)}")
            return True
        else:
            return False
            
    except:
        return False

def main_verification_process():
    """主验证流程
    原理：协调整个验证系统的运行流程
    运行流程：
    1. 初始化设备标识
    2. 尝试自动登录
    3. 获取系统公告
    4. 检查版本更新
    5. 显示菜单供用户选择
    6. 根据用户选择执行相应操作
    """
    print("至上原一验证·填写你的项目")
    
    # 初始化设备标识（必须成功）
    if initialize_device_identity() != 0:
        print("设备标识初始化失败")
        sys.exit(1)  # 设备标识初始化失败，退出程序
    
    # 尝试自动登录
    print("正在尝试自动登录...")
    if auto_login_function():
        print("自动登录成功，跳过验证流程")
        return
    
    # 获取系统公告
    retrieve_system_announcement_function()

    print("正在检查版本更新信息...")
    version_check_result = check_version_information_function()
    
    if version_check_result == 1:
        print("程序需要强制更新，即将退出...")
        time.sleep(2)
        sys.exit(0)
    elif version_check_result == 2:
        print("发现可用更新版本")
    elif version_check_result == 0:
        print("版本检查完成")

    # 主循环，等待用户选择
    while True:
        print("\n1. 登陆卡密")
        print("2. 解绑卡密")
        print("3. 退出")
        print("说明:请选择对应的序号，执行对应的操作。")
        
        try:
            user_selection = input("请选择功能: ").strip()
            if not user_selection:
                print("请输入有效选项")
                continue
                
            if user_selection.isdigit():
                user_selection = int(user_selection)
            else:
                print("请输入数字选项")
                continue
            
            if user_selection == 1:
                verification_result = verify_authorization_key_function()
                if verification_result == 200:
                    print("授权验证成功")
                    break
                else:
                    print("授权验证失败")
                    
            elif user_selection == 2:
                unbind_result = unbind_authorization_function()
                if unbind_result == 200:
                    print("授权解绑成功")
                    input("按回车键继续...")
                else:
                    print("授权解绑失败")
                    
            elif user_selection == 3:
                print("程序退出")
                sys.exit(0)
            else:
                print("无效的选项")
                
        except KeyboardInterrupt:
            print("\n程序已被用户中断")
            sys.exit(0)
        except Exception as e:
            print(f"系统异常: {str(e)}")
    
    print("验证流程完成，程序继续执行")

def main():
    """主函数
    原理：程序入口点，初始化并启动验证流程
    运行流程：
    1. 初始化随机数种子
    2. 调用主验证流程
    3. 验证成功后继续执行程序逻辑
    """
    print("程序启动初始化...")
    
    # 初始化随机数种子
    random.seed(int(time.time()))
    
    # 执行主验证流程
    main_verification_process()
    
    print("请在此处填写")
    
    print("按回车键退出程序...")
    input()

if __name__ == "__main__":
    main()

# 本实例由原一验证官方开发
# 禁止转载，否则后果自负。