from osgeo import gdal
import subprocess
import os

def generate_points_file(image_path, output_path="mouza_map.points"):
    # Example GCPs — adjust based on your map layout
    gcps = [
        {"pixelX": 100, "pixelY": 100, "mapX": 88.3639, "mapY": 22.5726},
        {"pixelX": 1000, "pixelY": 100, "mapX": 88.3739, "mapY": 22.5726},
        {"pixelX": 100, "pixelY": 1000, "mapX": 88.3639, "mapY": 22.5626},
        {"pixelX": 1000, "pixelY": 1000, "mapX": 88.3739, "mapY": 22.5626}
    ]
    with open(output_path, "w") as f:
        f.write("mapX,mapY,pixelX,pixelY,enable,order\n")
        for gcp in gcps:
            f.write(f"{gcp['mapX']},{gcp['mapY']},{gcp['pixelX']},{gcp['pixelY']},1,0\n")
    return output_path

def load_gcps(points_file):
    gcps = []
    with open(points_file, 'r') as f:
        for line in f:
            if line.startswith("#") or line.startswith("mapX"):
                continue
            parts = line.strip().split(",")
            if len(parts) < 4:
                continue
            mapX, mapY, pixelX, pixelY = map(float, parts[:4])
            gcps.append(gdal.GCP(mapX, mapY, 0, pixelX, pixelY))
    return gcps

def georeference_image(image_path, points_path, output_path="mouza_map_georef.tif"):
    gcps = load_gcps(points_path)
    temp_path = "temp_with_gcps.tif"
    gdal.Translate(temp_path, image_path, GCPs=gcps)
    gdal.Warp(output_path, temp_path, tps=True)
    return output_path

def generate_tiles(geotiff_path, tiles_dir="tiles_output"):
    subprocess.run([
        "gdal2tiles.py", "-z", "14-18", "-w", "google", geotiff_path, tiles_dir
    ])
    return tiles_dir