import pandas as pd
import numpy as np
import json

# 1. Load your data (Update this path if running locally outside Spotfire)
df = pd.read_csv('demo4_wafer_defects_with_zones.csv')

# 2. Dynamically calculate wafer dimensions from the data
# Assuming Die_X and Die_Y are your coordinate columns
min_x, max_x = df['Die_X'].min(), df['Die_X'].max()
min_y, max_y = df['Die_Y'].min(), df['Die_Y'].max()

center_x = (max_x + min_x) / 2.0
center_y = (max_y + min_y) / 2.0

# Calculate max radius of the wafer
df['radius'] = np.sqrt((df['Die_X'] - center_x)**2 + (df['Die_Y'] - center_y)**2)
max_radius = df['radius'].max()

# Based on your image, there are 4 radial zones (1 center + 3 rings)
num_radial_zones = 4
radii_boundaries = [max_radius * (i / num_radial_zones) for i in range(1, num_radial_zones + 1)]
center_radius = radii_boundaries[0] # The radius of the inner hollow circle

features = []

# --- A. DRAW THE RADIAL RINGS (Concentric Circles) ---
# We approximate circles using 100 points
angles = np.linspace(0, 2 * np.pi, 100)
for r in radii_boundaries:
    circle_coords = []
    for angle in angles:
        x = center_x + r * np.cos(angle)
        y = center_y + r * np.sin(angle)
        circle_coords.append([x, y])
    # Close the loop
    circle_coords.append(circle_coords[0])
    
    features.append({
        "type": "Feature",
        "properties": {"ZoneType": "Radial_Ring"},
        "geometry": {
            "type": "LineString",
            "coordinates": circle_coords
        }
    })

# --- B. DRAW THE ANGULAR CROSSHAIRS (Hollow Center) ---
# Right segment (X+)
features.append({
    "type": "Feature",
    "properties": {"ZoneType": "Angular_Crosshair"},
    "geometry": {"type": "LineString", "coordinates": [[center_x + center_radius, center_y], [center_x + max_radius, center_y]]}
})
# Left segment (X-)
features.append({
    "type": "Feature",
    "properties": {"ZoneType": "Angular_Crosshair"},
    "geometry": {"type": "LineString", "coordinates": [[center_x - max_radius, center_y], [center_x - center_radius, center_y]]}
})
# Top segment (Y+)
features.append({
    "type": "Feature",
    "properties": {"ZoneType": "Angular_Crosshair"},
    "geometry": {"type": "LineString", "coordinates": [[center_x, center_y + center_radius], [center_x, center_y + max_radius]]}
})
# Bottom segment (Y-)
features.append({
    "type": "Feature",
    "properties": {"ZoneType": "Angular_Crosshair"},
    "geometry": {"type": "LineString", "coordinates": [[center_x, center_y - max_radius], [center_x, center_y - center_radius]]}
})

# 3. Assemble GeoJSON
geojson_dict = {
    "type": "FeatureCollection",
    "features": features
}

# 4. Save to file
output_filename = "wafer_zone_crosshair.geojson"
with open(output_filename, 'w') as f:
    json.dump(geojson_dict, f, indent=2)

print(f"Successfully generated {output_filename} with hollow-center crosshairs!")