#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Aspose.CAD 版本和许可证状态检查脚本
功能：检查Aspose.CAD的安装状态、版本信息和许可证状态
作者：AI Assistant
日期：2024
"""

import os
import sys
import traceback
from pathlib import Path

def print_separator(title=""):
    """打印分隔线"""
    print("=" * 60)
    if title:
        print(f" {title} ")
        print("=" * 60)

def check_aspose_cad_installation():
    """检查Aspose.CAD安装状态"""
    print_separator("检查Aspose.CAD安装状态")
    
    try:
        # 尝试导入Aspose.CAD
        import aspose.cad as cad
        print("✓ 成功导入aspose.cad模块")
        
        # 检查版本信息
        version_info = {}
        
        # 方法1：检查模块的__version__属性
        if hasattr(cad, '__version__'):
            version_info['module_version'] = cad.__version__
            print(f"✓ 模块版本: {cad.__version__}")
        else:
            print("✗ 模块没有__version__属性")
        
        # 方法2：检查模块的__file__属性
        if hasattr(cad, '__file__'):
            module_path = cad.__file__
            print(f"✓ 模块路径: {module_path}")
            
            # 尝试从路径获取版本信息
            if 'site-packages' in module_path:
                parts = module_path.split('site-packages')
                if len(parts) > 1:
                    package_path = parts[1].strip('\\/')
                    print(f"✓ 包路径: {package_path}")
        
        # 方法3：检查模块的__path__属性
        if hasattr(cad, '__path__'):
            print(f"✓ 模块路径列表: {list(cad.__path__)}")
        
        # 方法4：尝试获取其他版本相关信息
        version_attrs = ['version', 'VERSION', 'version_info', 'VERSION_INFO']
        for attr in version_attrs:
            if hasattr(cad, attr):
                value = getattr(cad, attr)
                print(f"✓ {attr}: {value}")
                version_info[attr] = value
        
        return True, version_info
        
    except ImportError as e:
        print(f"✗ 导入失败: {e}")
        print("请确保已正确安装Aspose.CAD for Python")
        return False, {}
    except Exception as e:
        print(f"✗ 检查失败: {e}")
        return False, {}

def check_license_status():
    """检查许可证状态"""
    print_separator("检查许可证状态")
    
    try:
        import aspose.cad as cad
        
        # 方法1：检查是否有许可证相关的类或方法
        license_attrs = ['license', 'License', 'set_license', 'SetLicense']
        for attr in license_attrs:
            if hasattr(cad, attr):
                print(f"✓ 找到许可证相关属性: {attr}")
                try:
                    value = getattr(cad, attr)
                    print(f"  类型: {type(value).__name__}")
                    if callable(value):
                        print(f"  可调用: 是")
                    else:
                        print(f"  值: {value}")
                except Exception as e:
                    print(f"  访问失败: {e}")
        
        # 方法2：尝试创建许可证对象
        try:
            from aspose.cad import License
            print("✓ 成功导入License类")
            
            # 创建许可证实例
            license_obj = License()
            print(f"✓ 成功创建License实例: {type(license_obj).__name__}")
            
            # 检查许可证方法
            license_methods = ['set_license', 'SetLicense', 'is_licensed', 'IsLicensed']
            for method in license_methods:
                if hasattr(license_obj, method):
                    print(f"✓ 找到许可证方法: {method}")
                    try:
                        method_obj = getattr(license_obj, method)
                        if callable(method_obj):
                            print(f"  可调用: 是")
                            # 尝试调用is_licensed方法（如果存在）
                            if method.lower() == 'is_licensed':
                                try:
                                    is_licensed = method_obj()
                                    print(f"  许可证状态: {'已授权' if is_licensed else '未授权'}")
                                except Exception as e:
                                    print(f"  调用失败: {e}")
                    except Exception as e:
                        print(f"  访问失败: {e}")
            
            return True, license_obj
            
        except ImportError as e:
            print(f"✗ 无法导入License类: {e}")
            return False, None
        except Exception as e:
            print(f"✗ 创建License实例失败: {e}")
            return False, None
            
    except Exception as e:
        print(f"✗ 检查许可证状态失败: {e}")
        return False, None

def check_available_features():
    """检查可用功能"""
    print_separator("检查可用功能")
    
    try:
        import aspose.cad as cad
        
        # 检查主要功能模块
        modules_to_check = [
            'imageoptions',
            'fileformats',
            'Color',
            'Image',
            'CadRasterizationOptions',
            'PngOptions',
            'PdfOptions'
        ]
        
        available_modules = []
        for module_name in modules_to_check:
            try:
                if hasattr(cad, module_name):
                    module_obj = getattr(cad, module_name)
                    print(f"✓ {module_name}: {type(module_obj).__name__}")
                    available_modules.append(module_name)
                else:
                    print(f"✗ {module_name}: 不可用")
            except Exception as e:
                print(f"✗ {module_name}: 访问失败 - {e}")
        
        # 检查文件格式支持
        print("\n检查文件格式支持:")
        try:
            from aspose.cad import FileFormat
            if hasattr(FileFormat, 'values'):
                formats = FileFormat.values()
                print(f"✓ 支持的文件格式数量: {len(formats) if hasattr(formats, '__len__') else '未知'}")
            else:
                print("✗ 无法获取文件格式信息")
        except Exception as e:
            print(f"✗ 检查文件格式支持失败: {e}")
        
        return available_modules
        
    except Exception as e:
        print(f"✗ 检查可用功能失败: {e}")
        return []

def check_pip_package_info():
    """检查pip包信息"""
    print_separator("检查pip包信息")
    
    try:
        import subprocess
        import json
        
        # 使用pip show命令获取包信息
        result = subprocess.run([
            sys.executable, '-m', 'pip', 'show', 'aspose-cad'
        ], capture_output=True, text=True, encoding='utf-8')
        
        if result.returncode == 0:
            print("✓ pip包信息:")
            print(result.stdout)
            
            # 解析版本信息
            lines = result.stdout.split('\n')
            for line in lines:
                if line.startswith('Version:'):
                    version = line.split(':', 1)[1].strip()
                    print(f"✓ pip版本: {version}")
                    break
        else:
            print(f"✗ pip show失败: {result.stderr}")
            
        # 使用pip list命令检查所有相关包
        result = subprocess.run([
            sys.executable, '-m', 'pip', 'list', '--format=json'
        ], capture_output=True, text=True, encoding='utf-8')
        
        if result.returncode == 0:
            try:
                packages = json.loads(result.stdout)
                aspose_packages = [pkg for pkg in packages if 'aspose' in pkg['name'].lower()]
                if aspose_packages:
                    print(f"\n✓ 找到 {len(aspose_packages)} 个Aspose相关包:")
                    for pkg in aspose_packages:
                        print(f"  - {pkg['name']}: {pkg['version']}")
                else:
                    print("✗ 未找到Aspose相关包")
            except json.JSONDecodeError:
                print("✗ 无法解析pip list输出")
        else:
            print(f"✗ pip list失败: {result.stderr}")
            
    except Exception as e:
        print(f"✗ 检查pip包信息失败: {e}")

def check_system_info():
    """检查系统信息"""
    print_separator("检查系统信息")
    
    print(f"✓ Python版本: {sys.version}")
    print(f"✓ Python路径: {sys.executable}")
    print(f"✓ 操作系统: {os.name}")
    print(f"✓ 平台: {sys.platform}")
    
    # 检查Python路径
    print(f"✓ Python路径列表:")
    for path in sys.path:
        print(f"  - {path}")
    
    # 检查当前工作目录
    print(f"✓ 当前工作目录: {os.getcwd()}")

def test_basic_functionality():
    """测试基本功能"""
    print_separator("测试基本功能")
    
    try:
        import aspose.cad as cad
        from aspose.cad import Color
        
        print("✓ 成功导入基本模块")
        
        # 测试创建颜色对象
        try:
            color = Color.white
            print(f"✓ 成功创建颜色对象: {color}")
        except Exception as e:
            print(f"✗ 创建颜色对象失败: {e}")
        
        # 测试创建图像选项
        try:
            from aspose.cad.imageoptions import CadRasterizationOptions, PngOptions
            print("✓ 成功导入图像选项模块")
            
            # 测试创建光栅化选项
            raster_options = CadRasterizationOptions()
            print(f"✓ 成功创建光栅化选项: {type(raster_options).__name__}")
            
            # 测试创建PNG选项
            png_options = PngOptions()
            print(f"✓ 成功创建PNG选项: {type(png_options).__name__}")
            
        except Exception as e:
            print(f"✗ 测试图像选项失败: {e}")
        
        return True
        
    except Exception as e:
        print(f"✗ 测试基本功能失败: {e}")
        return False

def main():
    """主函数"""
    print_separator("Aspose.CAD 状态检查工具")
    print("此工具将检查Aspose.CAD的安装状态、版本信息和许可证状态")
    print()
    
    # 检查系统信息
    check_system_info()
    
    # 检查pip包信息
    check_pip_package_info()
    
    # 检查Aspose.CAD安装状态
    is_installed, version_info = check_aspose_cad_installation()
    
    if not is_installed:
        print("\n✗ Aspose.CAD未正确安装，无法继续检查")
        return
    
    # 检查许可证状态
    has_license, license_obj = check_license_status()
    
    # 检查可用功能
    available_modules = check_available_features()
    
    # 测试基本功能
    basic_works = test_basic_functionality()
    
    # 总结
    print_separator("检查总结")
    print(f"Aspose.CAD安装状态: {'✓ 已安装' if is_installed else '✗ 未安装'}")
    print(f"许可证状态: {'✓ 可用' if has_license else '✗ 不可用'}")
    print(f"基本功能: {'✓ 正常' if basic_works else '✗ 异常'}")
    print(f"可用模块数量: {len(available_modules)}")
    
    if version_info:
        print(f"\n版本信息:")
        for key, value in version_info.items():
            print(f"  {key}: {value}")
    
    if available_modules:
        print(f"\n可用模块:")
        for module in available_modules:
            print(f"  - {module}")
    
    # 建议
    print_separator("建议")
    if not is_installed:
        print("1. 请安装Aspose.CAD for Python:")
        print("   pip install aspose-cad")
    elif not has_license:
        print("1. 考虑获取Aspose.CAD许可证以获得完整功能")
        print("2. 检查许可证文件路径和设置")
    elif not basic_works:
        print("1. 检查Aspose.CAD版本兼容性")
        print("2. 尝试重新安装Aspose.CAD")
    else:
        print("✓ Aspose.CAD状态良好，可以正常使用")

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n\n用户中断了程序执行")
    except Exception as e:
        print(f"\n\n程序执行出错: {e}")
        traceback.print_exc()

