import ezdxf
import numpy as np

def analyze_dxf(filepath):
    print(f"Analyzing: {filepath}")
    doc = ezdxf.readfile(filepath)
    msp = doc.modelspace()
    
    points = []
    
    # 1. LWPOLYLINE, POLYLINE
    for entity in msp.query('LWPOLYLINE POLYLINE'):
        elevation = 0
        if hasattr(entity, 'dxf'):
            elevation = entity.dxf.elevation if hasattr(entity.dxf, 'elevation') else 0
        
        for p in entity.get_points():
            if len(p) >= 3:
                points.append((p[0], p[1], p[2]))
            else:
                points.append((p[0], p[1], elevation))

    # 2. LINE
    for entity in msp.query('LINE'):
        points.append(entity.dxf.start)
        points.append(entity.dxf.end)

    if not points:
        print("No points found!")
        return

    pts = np.array(points)
    min_vals = np.min(pts, axis=0)
    max_vals = np.max(pts, axis=0)
    ranges = max_vals - min_vals
    
    print("\n[Statistics]")
    print(f"Total points: {len(pts)}")
    print(f"X: {min_vals[0]:.2f} to {max_vals[0]:.2f} (Range: {ranges[0]:.2f})")
    print(f"Y: {min_vals[1]:.2f} to {max_vals[1]:.2f} (Range: {ranges[1]:.2f})")
    print(f"Z: {min_vals[2]:.2f} to {max_vals[2]:.2f} (Range: {ranges[2]:.2f})")
    
    # Ratio
    if ranges[0] > 0 and ranges[1] > 0:
        xy_avg_range = (ranges[0] + ranges[1]) / 2
        z_ratio = (ranges[2] / xy_avg_range) * 100
        print(f"Z-Ratio to XY: {z_ratio:.4f}%")
        if z_ratio < 0.1:
            print("WARNING: Z-range is extremely small compared to XY. Vertical exaggeration is required.")

if __name__ == "__main__":
    analyze_dxf('사연댐 전체계획 평면도_contour.dxf')
