"""Build a shareable F1 driver standings page with Python's standard library."""

import argparse
import json
from html import escape
from pathlib import Path
from tempfile import TemporaryDirectory
from urllib.error import URLError
from urllib.request import Request, urlopen


def load_standings(season):
    endpoint = f"https://api.jolpi.ca/ergast/f1/{season}/driverstandings/?limit=100"
    request = Request(endpoint, headers={"User-Agent": "F1-Standings-Toolkit/1.0"})
    with urlopen(request, timeout=30) as response:
        data = json.load(response)["MRData"]

    lists = data["StandingsTable"]["StandingsLists"]
    if not lists:
        raise ValueError("No standings published yet. Try a completed season, e.g. 2025.")
    standings = lists[0]
    drivers = standings["DriverStandings"]
    if not drivers or len(drivers) != int(data["total"]):
        raise ValueError("The data source returned an incomplete table. Try again later.")
    return standings


def render(standings):
    season = int(standings["season"])
    round_number = int(standings["round"])
    rows = []
    for entry in standings["DriverStandings"]:
        driver = entry["Driver"]
        name = escape(f'{driver["givenName"]} {driver["familyName"]}')
        position = escape(str(entry["position"]))
        points = escape(str(entry["points"]))
        rows.append(f'<tr><td>{position}</td><th scope="row">{name}</th><td>{points}</td></tr>')
    source = f"https://api.jolpi.ca/ergast/f1/{season}/{round_number}/driverstandings/?limit=100"
    return f"""<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>{season} F1 driver standings</title>
  <style>
    :root {{ color-scheme: light dark }}
    body {{ max-width: 36rem; margin: auto; padding: 2rem 1rem; font: 1rem/1.5 system-ui, sans-serif }}
    h1 {{ line-height: 1.15 }}
    table {{ width: 100%; border-collapse: collapse; font-variant-numeric: tabular-nums }}
    th, td {{ text-align: left; padding: .65rem .3rem; border-bottom: 1px solid #8888 }}
    th:last-child, td:last-child {{ text-align: right }}
    a {{ color: inherit }}
  </style>
</head>
<body><main>
  <h1>{season} F1 driver standings</h1>
  <p>Through round {round_number}</p>
  <table aria-label="Driver championship standings">
    <thead><tr><th scope="col">Rank</th><th scope="col">Driver</th><th scope="col">Points</th></tr></thead>
    <tbody>{''.join(rows)}</tbody>
  </table>
  <p>Data from <a href="{source}">Jolpica F1</a>.</p>
</main></body>
</html>
"""


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("season", type=int, nargs="?", help="year to look up (default: current season)")
    args = parser.parse_args()
    try:
        page = render(load_standings(args.season or "current"))
        output = Path(__file__).resolve().parent / "site" / "index.html"
        output.parent.mkdir(exist_ok=True)
        with TemporaryDirectory(dir=output.parent) as staging:
            temporary = Path(staging) / "index.html"
            temporary.write_text(page, encoding="utf-8")
            temporary.replace(output)
    except (URLError, OSError, ValueError, KeyError, TypeError) as error:
        raise SystemExit(f"Could not build the standings page: {error}") from None
    print(f"Open {output}")


if __name__ == "__main__":
    main()
