#!/usr/bin/env python3
"""
PLY文件格式检测脚本
用于诊断PLY文件的格式和内容
"""

import os
import sys

def detect_ply_format(ply_file_path):
    """
    检测PLY文件格式
    
    Args:
        ply_file_path: PLY文件路径
    """
    if not os.path.exists(ply_file_path):
        print(f"错误: 文件不存在: {ply_file_path}")
        return
    
    print(f"检测PLY文件: {ply_file_path}")
    print(f"文件大小: {os.path.getsize(ply_file_path)} 字节")
    
    try:
        # 尝试使用plyfile库
        from plyfile import PlyData
        print("\n使用plyfile库检测...")
        
        ply_data = PlyData.read(ply_file_path)
        print(f"PLY文件格式: {ply_data.header}")
        
        if 'vertex' in ply_data:
            vertex_data = ply_data['vertex'].data
            print(f"顶点数量: {len(vertex_data)}")
            print(f"顶点属性: {vertex_data.dtype.names}")
            
            # 显示前几个顶点的坐标
            if len(vertex_data) > 0:
                print("\n前3个顶点坐标:")
                for i in range(min(3, len(vertex_data))):
                    x, y, z = vertex_data[i]['x'], vertex_data[i]['y'], vertex_data[i]['z']
                    print(f"  顶点 {i}: ({x:.6f}, {y:.6f}, {z:.6f})")
        
        return True
        
    except ImportError:
        print("plyfile库未安装")
        return False
    except Exception as e:
        print(f"plyfile检测失败: {e}")
        return False

def manual_detect_format(ply_file_path):
    """
    手动检测PLY文件格式
    """
    print("\n手动检测文件格式...")
    
    try:
        with open(ply_file_path, 'rb') as f:
            # 读取文件头
            header_bytes = f.read(1024)
            
            # 尝试解码为ASCII
            try:
                header_text = header_bytes.decode('ascii', errors='ignore')
                print("文件头内容 (前500字符):")
                print(header_text[:500])
                
                if 'ply' in header_text.lower():
                    print("\n✓ 检测到PLY文件头")
                    
                    if 'format ascii' in header_text:
                        print("✓ 格式: ASCII")
                    elif 'format binary' in header_text:
                        print("✓ 格式: 二进制")
                    else:
                        print("? 格式: 未知")
                        
                    # 查找顶点数量
                    for line in header_text.split('\n'):
                        if 'element vertex' in line:
                            try:
                                num_vertices = int(line.split()[-1])
                                print(f"✓ 顶点数量: {num_vertices}")
                            except:
                                pass
                            break
                else:
                    print("✗ 未检测到PLY文件头")
                    
            except UnicodeDecodeError:
                print("✗ 文件包含非ASCII字符，可能是二进制格式")
                
    except Exception as e:
        print(f"手动检测失败: {e}")

def main():
    if len(sys.argv) != 2:
        print("用法: python test_ply_format.py <ply_file_path>")
        sys.exit(1)
    
    ply_file_path = sys.argv[1]
    
    # 使用plyfile库检测
    success = detect_ply_format(ply_file_path)
    
    # 手动检测
    manual_detect_format(ply_file_path)
    
    if not success:
        print("\n建议:")
        print("1. 安装plyfile库: pip install plyfile")
        print("2. 检查PLY文件是否损坏")
        print("3. 确认文件确实是PLY格式")

if __name__ == "__main__":
    main()
