#!/usr/bin/env python3
"""
Loads a location's roads GeoPackage, checks CRS, and reprojects
to an appropriate local UTM coordinate system for analysis.

✅ Features:
 - Works for any location (US states, countries, regions)
 - Auto-checks for missing files
 - Chooses a WGS84 UTM zone based on the location's centroid
 - Saves as {location}_roads_projected.gpkg
"""

import argparse
import sys
from pathlib import Path

import geopandas as gpd

from scripts.crs_utils import determine_utm_crs

def load_gpkg(path: Path, layer: str = None) -> gpd.GeoDataFrame:
    """Load a GeoPackage layer into a GeoDataFrame."""
    if layer:
        print(f"📦 Loading layer '{layer}' from {path}...")
        gdf = gpd.read_file(path, layer=layer)
    else:
        print(f"📦 Loading {path}...")
        gdf = gpd.read_file(path)
    print(f"✅ Loaded {len(gdf):,} features.")
    print(f"CRS: {gdf.crs}")
    return gdf

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Load a location's roads GeoPackage and reproject if needed."
    )
    parser.add_argument("location", help="Location name (e.g., alabama, belgium, france).")
    args = parser.parse_args()

    location = args.location.lower()
    
    # Check if location is in germany subdirectory first
    germany_dir = Path("output") / "germany" / location
    if (germany_dir / f"{location}_roads.gpkg").exists():
        base_dir = germany_dir
    else:
        base_dir = Path("output") / location
    
    input_path = base_dir / f"{location}_roads.gpkg"
    output_path = base_dir / f"{location}_roads_projected.gpkg"

    # Validate input
    if not input_path.exists():
        print(f"❌ File not found: {input_path}")
        sys.exit(1)

    # Load layer
    try:
        gdf = load_gpkg(input_path, "roads")
    except Exception as e:
        # Try loading without layer name
        print(f"⚠️ Could not load 'roads' layer, trying default layer...")
        gdf = load_gpkg(input_path)

    # Reproject to local UTM
    target_crs = determine_utm_crs(gdf)
    if gdf.crs != target_crs:
        gdf = gdf.to_crs(target_crs)
        print(f"🔁 Reprojected to local UTM ({target_crs.to_string()}).")
    else:
        print(f"✅ Already in target CRS: {target_crs}")

    # Save projected version
    gdf.to_file(output_path, layer="roads_projected", driver="GPKG")
    print(f"💾 Saved projected layer to: {output_path.resolve()}")
