import arcpy
import csv
import os

# Set up paths and spatial reference
output_folder = "C:/temp"
output_shapefile = os.path.join(output_folder, "prompt_1_data_subset.shp")
spatial_reference = arcpy.SpatialReference(2263)  # NAD83 / New York Long Island (ftUS)

try:
    # 1. Create the point shapefile with the specified spatial reference
    print("Creating point shapefile with NAD83 / New York Long Island (ftUS) projection...")
    arcpy.management.CreateFeatureclass(output_folder, "prompt_1_data_subset", "POINT", spatial_reference=spatial_reference)
    print(f"Shapefile created at {output_shapefile}")

    # Placeholder path for the CSV file - update with actual path
    csv_file = "C:/Users/BrianT/RIT/TEACHING/IGME_386_C_drive/Week_12_SDS_Predictive_Models/prompts/data_output/prompt_1_data_subset.csv"

    # Open the CSV file to read field names and data
    with open(csv_file, 'r') as file:
        csv_reader = csv.DictReader(file)
        fieldnames = csv_reader.fieldnames
        print("Fields found in CSV:", fieldnames)

        # 2. Add fields from CSV to the shapefile, including WktGeom
        print("Adding fields to the shapefile...")
        for field in fieldnames:
            # Define the field type
            if field == "Vol":
                # Vol field should be a long integer field
                arcpy.management.AddField(output_shapefile, field, "LONG")
            else:
                # Add other fields as text fields (including WktGeom)
                arcpy.management.AddField(output_shapefile, field, "TEXT", field_length=255)
        print("Fields added successfully.")

        # 3. Insert data from CSV into the shapefile
        print("Inserting points into the shapefile...")
        with arcpy.da.InsertCursor(output_shapefile, ["SHAPE@"] + fieldnames) as cursor:
            for row in csv_reader:
                # Read and parse WktGeom to get coordinates
                wkt_geom = row["WktGeom"]
                try:
                    # Extract X and Y from WktGeom in format "POINT (X Y)"
                    x, y = map(float, wkt_geom.replace("POINT (", "").replace(")", "").split())
                except ValueError:
                    print(f"Error parsing coordinates in WktGeom: {wkt_geom}")
                    continue  # Skip this row if coordinates cannot be parsed

                # Create a point geometry object
                point = arcpy.Point(x, y)

                # Convert Vol to a long integer if possible, handle conversion issues
                try:
                    row["Vol"] = int(row["Vol"])
                except ValueError:
                    row["Vol"] = None  # Set to None if Vol cannot be converted

                # Prepare the row data, inserting point geometry and other attributes
                cursor.insertRow([point] + [row[field] for field in fieldnames])
                
        print("Data insertion complete. All points added successfully.")

except arcpy.ExecuteError:
    # Handle geoprocessing errors specific to ArcPy
    print("ArcPy error:", arcpy.GetMessages(2))

except FileNotFoundError:
    # Handle file not found error for the CSV file
    print(f"Error: The CSV file was not found at {csv_file}. Please check the file path.")

except Exception as e:
    # Handle any other unexpected errors
    print("An unexpected error occurred:", str(e))

finally:
    # Confirm script completion
    print("Script execution complete.")
