#!/usr/bin/env python3
"""
Server orari autobus TPER.
Endpoints:
  GET /orari?linea=27&fermata=RESISTENZA&dir=0
  GET /fermate?linea=27
  GET /linee
"""
import json
import os
import sys
import uvicorn
from fastapi import FastAPI, Query
from fastapi.middleware.cors import CORSMiddleware

DB_PATH = os.path.join(os.path.dirname(__file__), "orari_db.json")

app = FastAPI(title="TPER Orari Bus", version="1.0")

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

# Load database
print(f"Loading {DB_PATH}...")
with open(DB_PATH, "r", encoding="utf-8") as f:
    db = json.load(f)
print(f"Loaded {len(db)} lines.")


@app.get("/linee")
def get_lines():
    """Return all line numbers."""
    return {"linee": sorted(db.keys(), key=lambda x: (int(x) if x.isdigit() else 999, x))}


@app.get("/fermate")
def get_stops(linea: str = Query(..., description="Linea (es: 27, 94, 357)")):
    """Return all stops for a line."""
    if linea not in db:
        return {"error": f"Linea {linea} non trovata"}
    
    line_data = db[linea]
    stops = {}
    for stop_name in sorted(line_data.keys(), key=str.lower):
        stop_info = line_data[stop_name]
        # Collect all available directions and services
        directions = {}
        for dir_id in sorted(stop_info.keys()):
            services = {}
            for label in sorted(stop_info[dir_id].keys()):
                num_trips = len(stop_info[dir_id][label])
                services[label] = num_trips
            directions[dir_id] = services
        stops[stop_name] = {"direzioni": directions}
    
    return {"linea": linea, "fermate": stops}


@app.get("/orari")
def get_times(
    linea: str = Query(..., description="Linea (es: 27, 94)"),
    fermata: str = Query(..., description="Nome fermata (es: RESISTENZA, ZAMBONI)"),
    dir: str = Query(None, description="Direzione (0=andata, 1=ritorno)"),
    servizio: str = Query(None, description="Servizio (Feriale, Sabato, Domenica)")
):
    """Return arrival times for a line at a stop."""
    if linea not in db:
        return {"error": f"Linea {linea} non trovata"}
    
    # Case-insensitive stop search
    line_data = db[linea]
    match = None
    for k in line_data:
        if k.upper() == fermata.upper() or fermata.upper() in k.upper():
            match = k
            break
    
    if not match:
        # Try partial match
        close_matches = [k for k in line_data if fermata.upper() in k.upper()]
        if close_matches:
            return {"error": f"Fermata '{fermata}' non trovata. Forse: {close_matches[:10]}?"}
        return {"error": f"Fermata '{fermata}' non trovata per linea {linea}"}
    
    stop_data = line_data[match]
    
    result = {}
    for dir_id in sorted(stop_data.keys()):
        if dir is not None and dir_id != dir:
            continue
        services = {}
        for label in sorted(stop_data[dir_id].keys()):
            if servizio and label.lower() != servizio.lower():
                continue
            services[label] = stop_data[dir_id][label]
        if services:
            result[f"direzione_{dir_id}"] = services
    
    return {
        "linea": linea,
        "fermata": match,
        "orari": result
    }


if __name__ == "__main__":
    port = int(sys.argv[1]) if len(sys.argv) > 1 else 8000
    uvicorn.run(app, host="0.0.0.0", port=port)
