"""Script to export route data from Supabase to update seed script."""
import os
from supabase import create_client, Client
from typing import Dict, Any
import json

def get_supabase_client() -> Client:
    """Create Supabase client from environment variables."""
    supabase_url = os.getenv("SUPABASE_URL")
    supabase_key = os.getenv("SUPABASE_ANON_KEY")
    
    if not supabase_url or not supabase_key:
        raise ValueError("SUPABASE_URL and SUPABASE_ANON_KEY must be set in environment")
    
    return create_client(supabase_url, supabase_key)

def export_route_data(route_name: str = "Boquete>David") -> Dict[str, Any]:
    """Export route data including all stops from Supabase."""
    supabase = get_supabase_client()
    
    # Get route
    route_response = supabase.table("routes").select("*").eq("name", route_name).execute()
    if not route_response.data:
        raise ValueError(f"Route '{route_name}' not found in Supabase")
    
    route = route_response.data[0]
    route_id = route["id"]
    
    # Get all route stops with stop details
    route_stops_response = supabase.table("route_stops").select(
        "*, bus_stops(*)"
    ).eq("route_id", route_id).order("stop_order").execute()
    
    route_stops = route_stops_response.data
    
    return {
        "route": route,
        "route_stops": route_stops,
        "total_stops": len(route_stops)
    }

def export_all_routes() -> Dict[str, Any]:
    """Export all routes and their stops from Supabase."""
    supabase = get_supabase_client()
    
    # Get all routes
    routes_response = supabase.table("routes").select("*").execute()
    routes = routes_response.data
    
    all_data = {}
    
    for route in routes:
        route_id = route["id"]
        route_name = route["name"]
        
        # Get all route stops
        route_stops_response = supabase.table("route_stops").select(
            "*, bus_stops(*)"
        ).eq("route_id", route_id).order("stop_order").execute()
        
        all_data[route_name] = {
            "route": route,
            "route_stops": route_stops_response.data,
            "total_stops": len(route_stops_response.data)
        }
    
    return all_data

if __name__ == "__main__":
    import sys
    
    if len(sys.argv) > 1 and sys.argv[1] == "--all":
        # Export all routes
        data = export_all_routes()
        output_file = "supabase_export_all.json"
    else:
        # Export specific route
        route_name = sys.argv[1] if len(sys.argv) > 1 else "Boquete>David"
        data = export_route_data(route_name)
        output_file = f"supabase_export_{route_name.replace('>', '_')}.json"
    
    # Save to JSON file
    with open(output_file, "w") as f:
        json.dump(data, f, indent=2, default=str)
    
    print(f"✅ Exported data to {output_file}")
    if isinstance(data, dict) and "total_stops" in data:
        print(f"   Total stops: {data['total_stops']}")
    elif isinstance(data, dict):
        for route_name, route_data in data.items():
            print(f"   {route_name}: {route_data['total_stops']} stops")

