"""Compare fixed scheduled trip counts in a local GTFS archive to a service plan."""
import argparse
import csv
from datetime import datetime
import io
import sys
from zipfile import ZipFile

WEEKDAYS = ("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday")

def read_rows(archive, name):
    with archive.open(name) as raw, io.TextIOWrapper(raw, encoding="utf-8-sig", newline="") as text:
        return list(csv.DictReader(text))

def unique(rows, columns):
    keys = [tuple(row[c] for c in columns) for row in rows]
    if len(keys) != len(set(keys)):
        raise ValueError(f"duplicate key in {', '.join(columns)}")

def active_services(date, calendar, exceptions):
    day = WEEKDAYS[datetime.strptime(date, "%Y%m%d").weekday()]
    active = {row["service_id"] for row in calendar
              if row["start_date"] <= date <= row["end_date"] and row[day] == "1"}
    for row in exceptions:
        if row["date"] == date:
            if row["exception_type"] == "1":
                active.add(row["service_id"])
            elif row["exception_type"] == "2":
                active.discard(row["service_id"])
            else:
                raise ValueError("invalid exception_type")
    return active

def compare(path, plan, output):
    with ZipFile(path) as archive:
        names = set(archive.namelist())
        if "frequencies.txt" in names and read_rows(archive, "frequencies.txt"):
            raise ValueError("This exercise counts fixed scheduled trips only.")
        if not {"calendar.txt", "calendar_dates.txt"} & names:
            raise ValueError("missing service calendar tables")
        cal = read_rows(archive, "calendar.txt") if "calendar.txt" in names else []
        exc = read_rows(archive, "calendar_dates.txt") if "calendar_dates.txt" in names else []
        trips = read_rows(archive, "trips.txt")
        routes = {r["route_id"] for r in read_rows(archive, "routes.txt")}
    unique(cal, ["service_id"])
    unique(exc, ["service_id", "date"])
    unique(trips, ["trip_id"])
    unique(plan, ["date","route_id"])
    if not plan:
        raise ValueError("empty service plan")
    writer = csv.writer(output, lineterminator="\n")
    writer.writerow(["date","route_id","planned_trips","actual_trips","delta","service_and_trip_ids"])
    passed = True
    for row in plan:
        date, route, expected = row["date"], row["route_id"], int(row["planned_trips"])
        if route not in routes:
            raise ValueError(f"unknown route {route}")
        active = active_services(date, cal, exc)
        matching = sorted((t["service_id"],t["trip_id"]) for t in trips
                          if t["route_id"] == route and t["service_id"] in active)
        count = len(matching)
        passed = passed and expected == count
        writer.writerow([date,route,expected,count,count-expected," ".join(f"{s}/{t}" for s,t in matching)])
    return passed

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("feed", help="local GTFS ZIP with tables at its root")
    parser.add_argument("plan", help="CSV with date,route_id,planned_trips")
    args = parser.parse_args()
    with open(args.plan, encoding="utf-8-sig", newline="") as handle:
        ok = compare(args.feed, list(csv.DictReader(handle)), sys.stdout)
    sys.exit(0 if ok else 1)
