print("Saving filtered data to a feature class using arcpy...")

output_gdb = "F:\\riyadh_places.gdb"  # Update with your actual path
output_fc = "riyadh_places_feature_class"

if not arcpy.Exists(output_gdb):
    arcpy.CreateFileGDB_management(*os.path.split(output_gdb))

spatial_ref = arcpy.SpatialReference(4326)

if not arcpy.Exists(f"{output_gdb}\\{output_fc}"):
    arcpy.CreateFeatureclass_management(
        out_path=output_gdb,
        out_name=output_fc,
        geometry_type="POINT",
        spatial_reference=spatial_ref
    )

fields = [
    ("id", "TEXT", 50),
    ("version", "SHORT"),
    ("sources", "TEXT", 255),
    ("names_pri", "TEXT", 255),
    ("names_com", "TEXT", 255),
    ("names_rul", "TEXT", 255),
    ("cat_pri", "TEXT", 255),
    ("cat_alt", "TEXT", 255),
    ("conf", "FLOAT"),
    ("websites", "TEXT", 255),
    ("socials", "TEXT", 255),
    ("emails", "TEXT", 255),
    ("phones", "TEXT", 255),
    ("brand_wik", "TEXT", 255),
    ("brand_pri", "TEXT", 255),
    ("brand_com", "TEXT", 255),
    ("brand_rul", "TEXT", 255),
    ("addresses", "TEXT", 255),
    ("theme", "TEXT", 255),
    ("type", "TEXT", 255),
]

for field_name, field_type, *field_length in fields:
    if not arcpy.ListFields(f"{output_gdb}\\{output_fc}", field_name):
        arcpy.AddField_management(f"{output_gdb}\\{output_fc}", field_name, field_type, field_length[0] if field_length else None)

max_length = 255

def truncate(value):
    if isinstance(value, str) and len(value) > max_length:
        return value[:max_length]
    return value

with arcpy.da.InsertCursor(f"{output_gdb}\\{output_fc}", ["SHAPE@XY"] + [f[0] for f in fields]) as cursor:
    for _, row in df.iterrows():
        geom = row['geometry']
        if isinstance(geom, Point):  # Ensure geometry is a Point
            cursor.insertRow([
                (geom.x, geom.y),
                row.get('id', ''),
                row.get('version', 0),
                truncate(json.dumps(row.get('sources', '')) if isinstance(row.get('sources', ''), dict) else row.get('sources', '')),
                row.get('names.primary', ''),
                truncate(json.dumps(row.get('names.common', '')) if isinstance(row.get('names.common', ''), dict) else row.get('names.common', '')),
                truncate(json.dumps(row.get('names.rules', '')) if isinstance(row.get('names.rules', ''), dict) else row.get('names.rules', '')),
                row.get('categories.primary', ''),
                truncate(','.join(row.get('categories.alternate', []) or []) if isinstance(row.get('categories.alternate', ''), list) else row.get('categories.alternate', '')),
                row.get('confidence', 0.0),
                truncate(','.join(row.get('websites', []) or []) if isinstance(row.get('websites', ''), list) else row.get('websites', '')),
                truncate(','.join(row.get('socials', []) or []) if isinstance(row.get('socials', ''), list) else row.get('socials', '')),
                truncate(','.join(row.get('emails', []) or []) if isinstance(row.get('emails', ''), list) else row.get('emails', '')),
                truncate(','.join(row.get('phones', []) or []) if isinstance(row.get('phones', ''), list) else row.get('phones', '')),
                row.get('brand.wikidata', ''),
                row.get('brand.names.primary', ''),
                truncate(json.dumps(row.get('brand.names.common', '')) if isinstance(row.get('brand.names.common', ''), dict) else row.get('brand.names.common', '')),
                truncate(json.dumps(row.get('brand.names.rules', '')) if isinstance(row.get('brand.names.rules', ''), dict) else row.get('brand.names.rules', '')),
                truncate(json.dumps(row.get('addresses', '')) if isinstance(row.get('addresses', ''), dict) else row.get('addresses', '')),
                row.get('theme', ''),
                row.get('type', '')
            ])

print(f"Feature class saved to {output_gdb}\\{output_fc}")
print("Process completed successfully!")

