# from chatGPT https://chatgpt.com/share/67e174e7-f5a4-8002-a502-5a16f00f0602
import csv
import json
import os
import sys
from collections import defaultdict


def load_stops(stops_file):
    """
    Load stops from the GTFS stops.txt file.
    Expects columns: stop_id, stop_lat, stop_lon.
    """
    stops = {}
    with open(stops_file, newline="", encoding="utf-8") as f:
        reader = csv.DictReader(f)
        for row in reader:
            stop_id = row["stop_id"]
            stops[stop_id] = {
                # Using "lattitude" as specified even though it's usually "latitude"
                "lattitude": float(row["stop_lat"]),
                "longitude": float(row["stop_lon"]),
            }
    return stops


def load_stop_times(stop_times_file):
    """
    Load stop_times and build a mapping from each stop_id to the set of trip_ids.
    """
    stop_to_trips = defaultdict(set)
    with open(stop_times_file, newline="", encoding="utf-8") as f:
        reader = csv.DictReader(f)
        for row in reader:
            stop_id = row["stop_id"]
            trip_id = row["trip_id"]
            stop_to_trips[stop_id].add(trip_id)
    return stop_to_trips


def create_json_files(stops, stop_to_trips, output_dir):
    """
    For each stop, create a JSON file following the specified structure.
    The filename is 'BCT_{stop_id}'.
    """
    os.makedirs(output_dir, exist_ok=True)
    for stop_id, info in stops.items():
        json_obj = {
            "_links": {
                "self": {"href": f"https://$base_domain/stops/BCT_{stop_id}"},
                "trips": [
                    {"href": f"https://$base_domain/trips/BCT_{trip_id}"}
                    for trip_id in sorted(stop_to_trips.get(stop_id, []))
                ],
            },
            "lattitude": info["lattitude"],
            "longitude": info["longitude"],
        }
        filename = os.path.join(output_dir, f"BCT_{stop_id}")
        with open(filename, "w", encoding="utf-8") as outfile:
            json.dump(json_obj, outfile, indent=2)
        print(f"Created {filename}")


def main():
    if len(sys.argv) != 4:
        print(
            "Usage: python gtfs_to_json.py <stops.txt> <stop_times.txt> <output_directory>"
        )
        sys.exit(1)

    stops_file = sys.argv[1]
    stop_times_file = sys.argv[2]
    output_dir = sys.argv[3]

    stops = load_stops(stops_file)
    stop_to_trips = load_stop_times(stop_times_file)
    create_json_files(stops, stop_to_trips, output_dir)


if __name__ == "__main__":
    main()
