"""
Télécharge les tuiles satellite autour de Verjux et assemble village.png
USAGE : python download_satellite.py
"""

import urllib.request
import math
import os
from PIL import Image

# ============================================================
#  CONFIGURATION
# ============================================================

# Centre du village de verdun sur le doubs
LAT = 46.8945173
LON = 5.0232693
# Zoom (15 = village entier, 16 = plus précis, 17 = très précis)
ZOOM = 17
# Nb de tuiles autour du centre (3 = grille 7x7, 4 = grille 9x9)
RADIUS = 8

OUTPUT = "village.png"

# ============================================================
#  FONCTIONS TUILES
# ============================================================

def lat_lon_to_tile(lat, lon, zoom):
    """Convertit GPS → numéro de tuile XYZ."""
    n = 2 ** zoom
    x = int((lon + 180) / 360 * n)
    y = int((1 - math.log(math.tan(math.radians(lat)) +
             1 / math.cos(math.radians(lat))) / math.pi) / 2 * n)
    return x, y

def tile_to_lat_lon(x, y, zoom):
    """Convertit numéro de tuile → GPS coin haut-gauche de la tuile."""
    n = 2 ** zoom
    lon = x / n * 360 - 180
    lat = math.degrees(math.atan(math.sinh(math.pi * (1 - 2 * y / n))))
    return lat, lon

def download_tile(x, y, zoom):
    """Télécharge une tuile satellite depuis Google Maps."""
    url = (f"https://mt1.google.com/vt/lyrs=s&x={x}&y={y}&z={zoom}")
    headers = {"User-Agent": "Mozilla/5.0"}
    req = urllib.request.Request(url, headers=headers)
    with urllib.request.urlopen(req, timeout=10) as r:
        data = r.read()
    # Sauvegarde temporaire
    tmp = f"_tile_{zoom}_{x}_{y}.png"
    with open(tmp, "wb") as f:
        f.write(data)
    return tmp

# ============================================================
#  MAIN
# ============================================================

center_x, center_y = lat_lon_to_tile(LAT, LON, ZOOM)

x_min = center_x - RADIUS
x_max = center_x + RADIUS
y_min = center_y - RADIUS
y_max = center_y + RADIUS

cols = x_max - x_min + 1
rows = y_max - y_min + 1
tile_size = 256  # pixels par tuile Google

print(f"Téléchargement {cols}x{rows} = {cols*rows} tuiles (zoom={ZOOM})...")

full_img = Image.new("RGB", (cols * tile_size, rows * tile_size))
tmp_files = []

for row_idx, ty in enumerate(range(y_min, y_max + 1)):
    for col_idx, tx in enumerate(range(x_min, x_max + 1)):
        print(f"  tuile ({tx}, {ty})...", end="\r")
        try:
            tmp = download_tile(tx, ty, ZOOM)
            tile_img = Image.open(tmp)
            full_img.paste(tile_img, (col_idx * tile_size, row_idx * tile_size))
            tmp_files.append(tmp)
        except Exception as e:
            print(f"\n  [WARN] Tuile ({tx},{ty}) échouée : {e}")

# Sauvegarde image finale
full_img.save(OUTPUT)
print(f"\n[OK] Image sauvegardée : {OUTPUT}")
print(f"     Taille : {full_img.size[0]}x{full_img.size[1]} px")

# Calcul coordonnées GPS des coins
lat_tl, lon_tl = tile_to_lat_lon(x_min,     y_min,     ZOOM)
lat_br, lon_br = tile_to_lat_lon(x_max + 1, y_max + 1, ZOOM)

print(f"\n[COORDONNÉES] Copie ces valeurs dans ctf_solver.py :")
print(f"  SAT_GPS_TL = ({lat_tl:.6f}, {lon_tl:.6f})")
print(f"  SAT_GPS_BR = ({lat_br:.6f}, {lon_br:.6f})")

# Nettoyage tuiles temporaires
for f in tmp_files:
    try:
        os.remove(f)
    except:
        pass

print("\nTerminé ! Lance maintenant : python ctf_solver.py")
