#!/usr/bin/env python3
# create_geotiff.py
# Requires: GDAL CLI installed. Python needs osgeo (from package 'gdal' or system Python with bindings).

from osgeo import gdal
import os
import sys

IMG = "img52.jpg"
TMP = "img52_with_gcps.tif"
OUT = "mouza_georef.tif"

# GCPs: (pixel_x, pixel_y, lon, lat)
gcps = [
    (1260, 1176, 88.533219, 22.763994),
    (584, 1253, 88.524254, 22.764192),
    (1564, 1494, 88.536393, 22.764033),
    (1943, 1586, 88.537841, 22.762965),
]

def main():
    if not os.path.exists(IMG):
        print("Image not found:", IMG); sys.exit(1)

    ds = gdal.Open(IMG)
    if ds is None:
        print("Cannot open image"); sys.exit(1)

    # Build GDAL GCP objects: gdal.GCP(GCPx, GCPy, GCPz, pixel, line)
    gcp_objs = []
    for px, py, lon, lat in gcps:
        gcp_objs.append(gdal.GCP(lon, lat, 0, px, py))

    # write temporary GeoTIFF with embedded GCPs
    gdal.Translate(TMP, ds, GCPs=gcp_objs, outputType=gdal.GDT_Byte)
    ds = None
    print("Wrote temporary with GCPs:", TMP)

    # Warp into proper georeferenced GeoTIFF (EPSG:4326) using TPS (good for scanned maps)
    warp_opts = gdal.WarpOptions(dstSRS='EPSG:4326', resampleAlg='bilinear', tps=True)
    gdal.Warp(OUT, TMP, options=warp_opts)
    print("Wrote georeferenced GeoTIFF:", OUT)

if __name__ == "__main__":
    main()
