#!/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_license_detailed():
    """详细检查许可证状态"""
    print_separator("详细许可证检查")
    
    try:
        import aspose.cad as cad
        from aspose.cad import License
        
        # 创建许可证对象
        license_obj = License()
        print(f"✓ 成功创建License实例: {type(license_obj).__name__}")
        
        # 检查许可证对象的所有属性和方法
        print("\n许可证对象的所有属性和方法:")
        for attr_name in dir(license_obj):
            if not attr_name.startswith('_'):
                try:
                    attr_value = getattr(license_obj, attr_name)
                    if callable(attr_value):
                        print(f"  方法: {attr_name}()")
                    else:
                        print(f"  属性: {attr_name} = {attr_value}")
                except Exception as e:
                    print(f"  属性: {attr_name} (访问失败: {e})")
        
        # 尝试检查许可证状态
        print("\n尝试检查许可证状态:")
        
        # 方法1：尝试调用is_licensed方法
        try:
            if hasattr(license_obj, 'is_licensed'):
                is_licensed = license_obj.is_licensed()
                print(f"✓ is_licensed(): {is_licensed}")
            else:
                print("✗ 没有is_licensed方法")
        except Exception as e:
            print(f"✗ 调用is_licensed失败: {e}")
        
        # 方法2：尝试调用IsLicensed方法
        try:
            if hasattr(license_obj, 'IsLicensed'):
                is_licensed = license_obj.IsLicensed()
                print(f"✓ IsLicensed(): {is_licensed}")
            else:
                print("✗ 没有IsLicensed方法")
        except Exception as e:
            print(f"✗ 调用IsLicensed失败: {e}")
        
        # 方法3：检查许可证相关属性
        license_props = ['is_licensed', 'IsLicensed', 'licensed', 'Licensed']
        for prop in license_props:
            try:
                if hasattr(license_obj, prop):
                    value = getattr(license_obj, prop)
                    print(f"✓ {prop}: {value}")
            except Exception as e:
                print(f"✗ 访问{prop}失败: {e}")
        
        return license_obj
        
    except Exception as e:
        print(f"✗ 详细许可证检查失败: {e}")
        return None

def test_license_restrictions():
    """测试许可证限制"""
    print_separator("测试许可证限制")
    
    try:
        import aspose.cad as cad
        from aspose.cad.imageoptions import CadRasterizationOptions, PngOptions
        from aspose.cad import Color
        
        # 测试1：尝试加载DWG文件
        print("测试1：尝试加载DWG文件")
        try:
            dwg_files = list(Path('.').glob('*.dwg'))
            if dwg_files:
                test_file = str(dwg_files[0])
                print(f"  使用文件: {test_file}")
                
                with cad.Image.load(test_file) as image:
                    print(f"  ✓ 成功加载DWG文件")
                    print(f"  图像尺寸: {image.width} x {image.height}")
                    
                    # 尝试转换
                    print("  尝试转换为PNG...")
                    try:
                        raster_options = CadRasterizationOptions()
                        raster_options.page_width = 800
                        raster_options.page_height = 600
                        raster_options.background_color = Color.white
                        
                        png_options = PngOptions()
                        png_options.vector_rasterization_options = raster_options
                        
                        output_path = "test_output.png"
                        image.save(output_path, png_options)
                        
                        if os.path.exists(output_path):
                            file_size = os.path.getsize(output_path)
                            print(f"  ✓ 转换成功，输出文件大小: {file_size} 字节")
                            
                            # 检查是否有水印
                            if file_size > 0:
                                print(f"  ✓ 文件大小正常，可能没有水印限制")
                            else:
                                print(f"  ✗ 文件大小为0，可能有许可证限制")
                            
                            # 清理测试文件
                            try:
                                os.remove(output_path)
                                print(f"  ✓ 已清理测试文件")
                            except:
                                pass
                        else:
                            print(f"  ✗ 转换失败，未生成输出文件")
                            
                    except Exception as e:
                        print(f"  ✗ 转换失败: {e}")
                        if "evaluation" in str(e).lower() or "trial" in str(e).lower():
                            print(f"    → 这可能是评估版限制")
                        elif "license" in str(e).lower():
                            print(f"    → 这可能是许可证问题")
            else:
                print("  ✗ 未找到DWG文件进行测试")
                
        except Exception as e:
            print(f"  ✗ 加载DWG文件失败: {e}")
            if "evaluation" in str(e).lower() or "trial" in str(e).lower():
                print(f"    → 这可能是评估版限制")
            elif "license" in str(e).lower():
                print(f"    → 这可能是许可证问题")
        
        # 测试2：检查是否有评估版水印
        print("\n测试2：检查评估版水印")
        try:
            # 创建一个简单的测试图像
            from aspose.cad import Color
            from aspose.cad.imageoptions import CadRasterizationOptions, PngOptions
            
            # 尝试创建一个简单的CAD图像
            print("  尝试创建测试图像...")
            # 这里可以添加更多测试逻辑
            
        except Exception as e:
            print(f"  ✗ 测试评估版水印失败: {e}")
        
    except Exception as e:
        print(f"✗ 测试许可证限制失败: {e}")

def check_evaluation_limitations():
    """检查评估版限制"""
    print_separator("检查评估版限制")
    
    try:
        import aspose.cad as cad
        
        # 检查是否有评估版相关的属性或方法
        eval_attrs = ['evaluation', 'trial', 'demo', 'watermark']
        
        print("检查评估版相关属性:")
        for attr in eval_attrs:
            if hasattr(cad, attr):
                value = getattr(cad, attr)
                print(f"  ✓ {attr}: {value}")
            else:
                print(f"  ✗ {attr}: 不存在")
        
        # 检查模块文档字符串
        if hasattr(cad, '__doc__') and cad.__doc__:
            doc = cad.__doc__
            if 'evaluation' in doc.lower() or 'trial' in doc.lower():
                print(f"  ⚠ 模块文档中提到评估版/试用版")
                print(f"    文档片段: {doc[:200]}...")
        
        # 检查版本信息
        if hasattr(cad, 'VERSION'):
            version = cad.VERSION
            print(f"  版本: {version}")
            
            # 检查版本号是否包含评估版标识
            if 'eval' in str(version).lower() or 'trial' in str(version).lower():
                print(f"  ⚠ 版本号包含评估版标识")
        
    except Exception as e:
        print(f"✗ 检查评估版限制失败: {e}")

def check_watermark_info():
    """检查水印信息"""
    print_separator("检查水印信息")
    
    try:
        import aspose.cad as cad
        
        # 检查是否有水印相关的类或方法
        watermark_attrs = ['watermark', 'Watermark', 'evaluation_watermark', 'trial_watermark']
        
        print("检查水印相关属性:")
        for attr in watermark_attrs:
            if hasattr(cad, attr):
                value = getattr(cad, attr)
                print(f"  ✓ {attr}: {value}")
            else:
                print(f"  ✗ {attr}: 不存在")
        
        # 检查图像选项中是否有水印相关设置
        try:
            from aspose.cad.imageoptions import CadRasterizationOptions
            raster_options = CadRasterizationOptions()
            
            print("\n检查光栅化选项中的水印设置:")
            for attr_name in dir(raster_options):
                if not attr_name.startswith('_') and 'watermark' in attr_name.lower():
                    try:
                        value = getattr(raster_options, attr_name)
                        print(f"  ✓ {attr_name}: {value}")
                    except Exception as e:
                        print(f"  ✗ {attr_name}: 访问失败 - {e}")
                        
        except Exception as e:
            print(f"✗ 检查光栅化选项失败: {e}")
        
    except Exception as e:
        print(f"✗ 检查水印信息失败: {e}")

def main():
    """主函数"""
    print_separator("Aspose.CAD 许可证详细检查工具")
    print("此工具将详细检查Aspose.CAD的许可证状态和限制")
    print()
    
    # 详细许可证检查
    license_obj = check_license_detailed()
    
    # 检查评估版限制
    check_evaluation_limitations()
    
    # 检查水印信息
    check_watermark_info()
    
    # 测试许可证限制
    test_license_restrictions()
    
    # 总结
    print_separator("许可证检查总结")
    print("基于以上检查结果，您可以判断:")
    print("1. 如果转换成功且文件大小正常 → 可能已获得有效许可证")
    print("2. 如果转换失败或出现评估版错误 → 可能需要购买许可证")
    print("3. 如果输出文件包含水印 → 这是评估版的正常行为")
    print("\n建议:")
    print("- 如果需要商业使用，请购买Aspose.CAD许可证")
    print("- 评估版通常有功能限制或水印")
    print("- 联系Aspose技术支持获取许可证相关帮助")

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