"""Read only the needed columns of the TLC High Volume FHV monthly trip files, remotely, and keep aggregates.

Never downloads a whole file. The footer is read first; then, for each row group, only the byte spans holding the
needed column chunks are fetched with HTTP range requests (adjacent chunks closer than GAP bytes share one request, so a
file costs about 75 requests). Each row group is aggregated as soon as it arrives and its bytes are dropped.

Usage: aggregate.py <YYYY-MM> <zones.json> <out.parquet> [counts]
With "counts" (used for the placebo years 2022 and 2023) only pickup time and the two zones are read, and the money,
fee, miles and seconds columns are left empty.
Output rows: pickup date x hour x pickup zone x drop-off class (2 fee zone, 1 boundary zone, 0 outside), with trips,
trips carrying the zone fee and sums of fare, driver pay, tips, zone fee, miles and trip seconds.
Prints one JSON line: the columns read, file bytes, bytes fetched, requests and seconds.
"""
import io
import json
import sys
import time
import urllib.request

import duckdb
import pyarrow.parquet as pq

URL = "https://d37ci6vzurychx.cloudfront.net/trip-data/fhvhv_tripdata_{ym}.parquet"
WANT = ["pickup_datetime", "PULocationID", "DOLocationID", "trip_miles", "trip_time", "base_passenger_fare",
        "driver_pay", "tips", "cbd_congestion_fee"]
GAP = 512 * 1024
UA = {"User-Agent": "study-aggregator/1.0"}


class Remote(io.RawIOBase):
    """A read-only file over HTTP range requests, served from prefetched spans."""

    def __init__(self, url):
        self.url, self.pos, self.spans, self.requests, self.fetched = url, 0, [], 0, 0
        req = urllib.request.Request(url, method="HEAD", headers=UA)
        with urllib.request.urlopen(req, timeout=60) as r:
            self.size = int(r.headers["Content-Length"])
        self.requests += 1

    def fetch(self, start, end):
        req = urllib.request.Request(self.url, headers={**UA, "Range": f"bytes={start}-{end - 1}"})
        with urllib.request.urlopen(req, timeout=300) as r:
            data = r.read()
        assert len(data) == end - start, (len(data), start, end)
        self.requests += 1
        self.fetched += len(data)
        self.spans.append((start, data))

    def drop(self, keep_footer_from):
        self.spans = [(s, d) for s, d in self.spans if s >= keep_footer_from]

    def readable(self):
        return True

    def seekable(self):
        return True

    def tell(self):
        return self.pos

    def seek(self, off, whence=0):
        self.pos = off if whence == 0 else (self.pos + off if whence == 1 else self.size + off)
        return self.pos

    def readinto(self, b):
        n = min(len(b), self.size - self.pos)
        for s, d in self.spans:
            if s <= self.pos and self.pos + n <= s + len(d):
                b[:n] = d[self.pos - s:self.pos - s + n]
                self.pos += n
                return n
        self.fetch(self.pos, self.pos + n)
        return self.readinto(b)


def plan(meta, rg, cols):
    names = [meta.schema.column(i).name for i in range(meta.num_columns)]
    chunks = []
    for c in cols:
        cc = meta.row_group(rg).column(names.index(c))
        start = cc.dictionary_page_offset if cc.has_dictionary_page and cc.dictionary_page_offset else cc.data_page_offset
        chunks.append((start, start + cc.total_compressed_size))
    chunks.sort()
    spans = [list(chunks[0])]
    for s, e in chunks[1:]:
        if s - spans[-1][1] <= GAP:
            spans[-1][1] = max(spans[-1][1], e)
        else:
            spans.append([s, e])
    return spans


def aggregate(ym, zones_path, out, counts_only=False):
    t = time.time()
    zj = json.load(open(zones_path))
    zl = ",".join(str(int(z)) for z in zj["fee_zone_location_ids"])
    bl = ",".join(str(int(z)) for z in zj["boundary_location_ids"])
    f = Remote(URL.format(ym=ym))
    tail = min(f.size, 2 * 1024 * 1024)
    f.fetch(f.size - tail, f.size)
    pf = pq.ParquetFile(f)
    names = [pf.metadata.schema.column(i).name for i in range(pf.metadata.num_columns)]
    cols = [c for c in (WANT[:3] if counts_only else WANT) if c in names]
    fee = "cbd_congestion_fee" if "cbd_congestion_fee" in cols else "0.0"
    money = {k: ("NULL" if counts_only else v) for k, v in {
        "fare": "base_passenger_fare", "pay": "driver_pay", "tips": "tips", "miles": "trip_miles",
        "secs": "trip_time"}.items()}
    if counts_only:
        fee = "NULL"
    con = duckdb.connect()
    con.execute("SET threads=2")
    parts = []
    for rg in range(pf.num_row_groups):
        for s, e in plan(pf.metadata, rg, cols):
            f.fetch(s, e)
        tbl = pf.read_row_group(rg, columns=cols)
        parts.append(con.execute(f"""SELECT
            CAST(pickup_datetime AS DATE) AS day, CAST(hour(pickup_datetime) AS TINYINT) AS hour,
            CAST(PULocationID AS SMALLINT) AS pu,
            CAST(CASE WHEN DOLocationID IN ({zl}) THEN 2 WHEN DOLocationID IN ({bl}) THEN 1 ELSE 0 END AS TINYINT)
              AS do_class,
            count(*) AS trips, count(*) FILTER (WHERE {fee} > 0) AS fee_trips,
            round(sum({money['fare']}) * 100) AS fare_cents, round(sum({money['pay']}) * 100) AS driver_pay_cents,
            round(sum({money['tips']}) * 100) AS tips_cents, round(sum({fee}) * 100) AS zone_fee_cents,
            round(sum({money['miles']}) * 100) AS miles_x100, sum({money['secs']}) AS trip_seconds
            FROM tbl GROUP BY ALL""").to_arrow_table())
        f.drop(f.size - tail)
        del tbl
    import pyarrow as pa
    allp = pa.concat_tables(parts)
    con.execute(f"""COPY (SELECT day, hour, pu, do_class, CAST(sum(trips) AS INTEGER) AS trips,
        CAST(sum(fee_trips) AS INTEGER) AS fee_trips, CAST(sum(fare_cents) AS BIGINT) AS fare_cents,
        CAST(sum(driver_pay_cents) AS BIGINT) AS driver_pay_cents, CAST(sum(tips_cents) AS BIGINT) AS tips_cents,
        CAST(sum(zone_fee_cents) AS BIGINT) AS zone_fee_cents, CAST(sum(miles_x100) AS BIGINT) AS miles_x100,
        CAST(sum(trip_seconds) AS BIGINT) AS trip_seconds
        FROM allp GROUP BY ALL ORDER BY day, hour, pu, do_class) TO '{out}' (FORMAT PARQUET, COMPRESSION ZSTD)""")
    rows = int(pf.metadata.num_rows)
    return {"month": ym, "url": URL.format(ym=ym), "columns_read": cols, "file_rows": rows, "file_bytes": f.size,
            "bytes_fetched": f.fetched, "requests": f.requests, "seconds": round(time.time() - t, 1)}


if __name__ == "__main__":
    print(json.dumps(aggregate(sys.argv[1], sys.argv[2], sys.argv[3], len(sys.argv) > 4 and sys.argv[4] == "counts")))
