aboutsummaryrefslogtreecommitdiffstats
path: root/fnme/cli.py
blob: 5437ff080a7aaa6c967b3d575181d95e64d4b395 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import argparse
import sys
from typing import Any

from tabulate import tabulate

from fnme.constants import SORT_KV
from fnme.data import get_latest_data
from fnme.exceptions import DataFetchError, LocationError
from fnme.geo import get_location
from fnme.station import process_stations, sort_stations

_PRICE_COLS = {
    "e5_price": "E5 (£/L)",
    "e10_price": "E10 (£/L)",
    "diesel_price": "B7S (£/L)",
}

_HEADERS = {
    "station_name": "Station Name",
    "distance": "Distance (mi)",
    **_PRICE_COLS,
}


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser()
    parser.add_argument("-a", "--address", type=str, required=True)
    parser.add_argument("-r", "--radius", type=int, default=5)
    parser.add_argument(
        "-s", "--sort", type=str, default="e10", choices=SORT_KV.keys()
    )
    return parser.parse_args()


def _fmt_price(v: float | None) -> str:
    return f"{v:.2f}" if v is not None else "N/A"


def output_stations(stations: list[dict[str, Any]]) -> None:
    if not stations:
        print("[*] No stations found.")
        return

    rows = [
        {**s, **{col: _fmt_price(s[col]) for col in _PRICE_COLS}}
        for s in stations
    ]

    print(tabulate(rows, headers=_HEADERS, floatfmt="1.f"))


def main():
    args = parse_args()

    try:
        location = get_location(args.address)
        print(f"[✔] Coordinates found: {args.address}")
    except LocationError as e:
        print(f"Error: {e.message}")
        print("Check the spelling of the address or try a different address.")
        sys.exit(1)
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
        sys.exit(1)

    try:
        df, last_modified = get_latest_data()
    except DataFetchError as e:
        print(f"Error: {e.message}")
        print(
            "Check your internet connection or verify that this script can access the cache location."
        )
        sys.exit(1)
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
        sys.exit(1)

    print(f"Last updated: {last_modified}")

    df_filtered = process_stations(df, args.radius, location)

    sorted_stations_list = sort_stations(df_filtered, args.sort)

    output_stations(sorted_stations_list)


if __name__ == "__main__":
    main()
git.ajschof.me — hosted by ajschofield — powered by cgit