#!/usr/bin/env python3
"""
Loads extracted buildings GeoPackage and reprojects to a local UTM CRS for analysis.

This script complements load_gpkg.py by handling buildings data specifically.
It reprojects buildings from WGS84 to a meter-based UTM coordinate system
suitable for spatial analysis and grid aggregation.
"""

import argparse
import sys
import os
from pathlib import Path

# Fix GeoPandas compatibility issues
os.environ['USE_PYGEOS'] = '0'
import geopandas as gpd

from scripts.crs_utils import determine_utm_crs

def load_buildings_gpkg(state: str):
    state = state.lower()
    base_dir = Path.cwd()
    state_dir = base_dir / "output" / state
    
    input_path = state_dir / f"{state}_buildings.gpkg"
    output_path = state_dir / f"{state}_buildings_projected.gpkg"
    
    if not input_path.exists():
        print(f"❌ Buildings file not found: {input_path}")
        print("   Run extract_state_buildings.py first to extract buildings.")
        sys.exit(1)
    
    print(f"📦 Loading buildings data from {input_path.name}...")
    
    try:
        # Load buildings
        buildings = gpd.read_file(input_path, layer="buildings")
        print(f"✅ Loaded {len(buildings):,} buildings")
        print(f"📋 Current CRS: {buildings.crs}")
        
        target_crs = determine_utm_crs(buildings)
        if buildings.crs != target_crs:
            print(f"🔄 Reprojecting to local UTM ({target_crs.to_string()})...")
            buildings = buildings.to_crs(target_crs)
            print("✅ Reprojection complete")
        else:
            print("✅ Buildings already in target CRS")
        
        # Save reprojected data
        buildings.to_file(output_path, layer="buildings_projected", driver="GPKG")
        print(f"💾 Saved projected buildings to: {output_path.name}")
        
        # Show sample data
        print(f"\n📋 Building attributes available:")
        for col in buildings.columns:
            if col != 'geometry':
                non_null_count = buildings[col].notna().sum()
                print(f"  {col}: {non_null_count:,} non-null values")
        
        print(f"\n🔍 Sample buildings data:")
        print(buildings.head())
        
    except Exception as e:
        print(f"❌ Processing failed: {e}")
        sys.exit(1)
    
    print("\n✅ Buildings processing complete!")
    print(f"📁 Folder: {state_dir}")
    print(f"📥 Input: {input_path.name}")
    print(f"💾 Output: {output_path.name}")
    print("🔄 Next: Run visualize_all_attribute_grid.py to generate building heatmaps")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Load and reproject extracted building footprints for a state."
    )
    parser.add_argument("state", help="State name (e.g., alabama).")
    args = parser.parse_args()

    load_buildings_gpkg(args.state)
