import requests, json
import v
from v import *

def lo_lookup(operator, station, country="uk"):

    print(station)
    station = station.replace(" ", "%20")

    try:
        data = requests.get("https://api.tfl.gov.uk/StopPoint/Search/" + station).text
    except Exception as e:
        print("Error.", e)
        return {}

    data = json.loads(data)
    search_list = {}
    print(data)
    VALID_TFL_MODES = [ "tube", "overground", "elizabeth-line", "dlr", "tram", "bus", "river-bus" ]
    try:
        matches = data["matches"]

        for m in matches:
            name = m["name"]
            siteid = m["id"]
            modes = m.get("modes", [])
            if not any(mode in VALID_TFL_MODES for mode in modes): continue
            if "HUB" in siteid: continue

            # Store in your v.sites structure
            v.sites[country][operator][name] = siteid

            # Add to return list
            search_list[name] = siteid

    except Exception as e:
        print("Search-Error:", e)

    print(search_list)
    return search_list




def lo_load_departures(station_id, operator, country="uk"):
    try:
        data = requests.get(
            f"https://api.tfl.gov.uk/StopPoint/{station_id}/Arrivals"
        ).text
    except Exception as e:
        print("Error:", e)
        return []

    arrivals = json.loads(data)
    results = []

    for a in arrivals:
        try:
            destination = a.get("destinationName", "")
            line = a.get("lineName", "")
            mode = a.get("modeName", "").lower()
            expected = a.get("expectedArrival", "")

            # Normalize transport mode
            if "bus" in mode:
                mode = "bus"
            elif "tube" in mode:
                mode = "metro"
            elif "dlr" in mode:
                mode = "metro"
            elif "overground" in mode:
                mode = "train"
            elif "tram" in mode:
                mode = "tram"
            elif "river" in mode:
                mode = "ship"
            else:
                mode = "train"

            new_record = {
                "destination": destination,
                "direction_code": "0",
                "expected": expected.replace("Z", ""),
                "line": {
                    "id": line,
                    "transport_mode": mode.upper()
                },
                "deviations": []
            }

            results.append(new_record)
            if len(results) > 50:
                break

        except Exception as e:
            print("Error:", e)
            continue

    if results:
        v.operators[country][operator][station_id]["departures"] = results
        return results

    return []
