#!/usr/bin/env python3
"""Reproduce the four Poly Tick Tape archive studies using daily JSONL.gz files.

Place btc-{price,twap60}-YYYY-MM-DD.jsonl.gz in ROOT/YYYY-MM-DD/. Include
one extra TWAP60 day for the final midnight boundary and positive offsets.
Example: python3 -I btc-5m-data-quality.py ROOT OUTPUT --from 2026-08-14 --to 2026-10-18
No interpolation, no API keys, no network. Outputs aggregate statistics only.
"""
import argparse
from bisect import bisect_right
import csv
from datetime import date, timedelta
from decimal import Decimal
import gzip
import json
from pathlib import Path
from statistics import median

OFFSETS = (-5, -2, -1, 1, 2, 5)
DAY = timedelta(days=1)
SECONDS = 86_400


def epoch(day):
    return (day - date(1970, 1, 1)).days * SECONDS


def read(root, stream, day):
    path = root / str(day) / f'btc-{stream}-{day}.jsonl.gz'
    rows = {}
    with gzip.open(path, 'rt', encoding='utf-8') as file:
        for line in file:
            row = json.loads(line)
            second = row['ts']
            if second in rows or not epoch(day) <= second < epoch(day) + SECONDS:
                raise ValueError(f'{path}: duplicate or out-of-day second {second}')
            rows[second] = (Decimal(row['p']), row['feed_ts_ms'], row['recv_ms'])
    return rows


def different(opening, closing, alternative):
    return (closing >= opening) != (alternative >= opening)


def largest_gap(seconds, start, end):
    return max((b - a - 1 for a, b in zip([start - 1, *seconds], [*seconds, end])), default=0)


def summarize(values):
    # Strings preserve decimal arithmetic in source; presentation is rounded to cents.
    return {'medianUsd': str(round(median(values), 2)), 'maxUsd': str(round(max(values), 2))} if values else None


def study(root, first, last):
    daily = []
    offset = dict.fromkeys(OFFSETS, 0)
    offset_rounds = 0
    receipt = {'checks': 0, 'comparable': 0, 'differentRows': 0, 'differentValues': 0}
    receipt_gaps = []
    groups = {name: {'rounds': 0, 'flips': 0, 'errors': []} for name in ('complete', 'withGaps')}
    mean_skipped = 0
    t = read(root, 'twap60', first)
    price = read(root, 'price', first)
    previous_price = {}
    day = first
    while day <= last:
        start = epoch(day)
        end = start + SECONDS
        following = read(root, 'twap60', day + DAY)
        all_t = t | {s: following[s] for s in range(end, end + 6) if s in following}
        p = previous_price | price
        # Only the next midnight price is needed for the final rolling mean of this day.
        # The extra date is read once per day and reused as the main file next time.
        next_price = read(root, 'price', day + DAY)
        if end in next_price:
            p[end] = next_price[end]

        times = sorted(t)
        events = sorted(t.values(), key=lambda row: (row[1], row[2]))
        # Both clocks must be at or before the cut, even if they disagree.
        arrivals = sorted(t.values(), key=lambda row: (max(row[1:]), row[1], row[2]))
        event_times = [row[1] for row in events]
        arrived = 0
        latest = None
        usable = 0
        means = {}
        for boundary in range(start, end + 1, 300):
            if boundary - 59 < epoch(first):
                continue  # not an observed gap: the window extends outside the sample
            prices = [p[u][0] for u in range(boundary - 59, boundary + 1) if u in p]
            if prices:
                means[boundary] = (sum(prices) / len(prices), len(prices))
        for s in range(start, end, 300):
            close = s + 300
            if s in all_t and close in all_t:
                usable += 1
                a, b = all_t[s][0], all_t[close][0]
                if all(close + n in all_t for n in OFFSETS):
                    offset_rounds += 1
                    for n in OFFSETS:
                        offset[n] += different(a, b, all_t[close + n][0])
                if s in means and close in means:
                    x, nx = means[s]
                    y, ny = means[close]
                    group = groups['complete' if nx == ny == 60 else 'withGaps']
                    group['rounds'] += 1
                    group['flips'] += (b >= a) != (y >= x)
                    group['errors'].extend((abs(a - x), abs(b - y)))
                else:
                    mean_skipped += 1

            cut = (s + 240) * 1000
            receipt['checks'] += 1
            i = bisect_right(event_times, cut) - 1
            while arrived < len(arrivals) and max(arrivals[arrived][1:]) <= cut:
                candidate = arrivals[arrived]
                if latest is None or candidate[1:] > latest[1:]:
                    latest = candidate
                arrived += 1
            if i >= 0 and latest is not None and cut - latest[1] <= 30_000:
                naive = events[i]
                receipt['comparable'] += 1
                receipt['differentRows'] += naive[1] != latest[1]
                receipt['differentValues'] += naive[0] != latest[0]
                receipt_gaps.append(abs(naive[0] - latest[0]))

        daily.append({'date': str(day), 'twap60_seconds': len(t), 'usable_rounds': usable,
                      'missing_boundary_rounds': 288 - usable, 'longest_gap_seconds': largest_gap(times, start, end)})
        previous_price = {s: price[s] for s in range(end - 59, end) if s in price}
        price, t = next_price, following
        day += DAY

    return daily, {
        'from': str(first), 'to': str(last), 'days': len(daily),
        'coverage': {'scheduledRounds': len(daily) * 288, 'usableRounds': sum(r['usable_rounds'] for r in daily),
                     'twap60Seconds': sum(r['twap60_seconds'] for r in daily),
                     'expectedSeconds': len(daily) * SECONDS,
                     'completeRoundDays': sum(r['usable_rounds'] == 288 for r in daily),
                     'maxDailyGap': max(r['longest_gap_seconds'] for r in daily)},
        'offset': {'rounds': offset_rounds, 'flips': offset},
        'receipt': receipt | {'absoluteDifference': summarize(receipt_gaps)},
        'mean': {name: {'rounds': g['rounds'], 'flips': g['flips'], 'boundaryError': summarize(g['errors'])}
                 for name, g in groups.items()} | {'skippedRounds': mean_skipped},
    }


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('root', type=Path)
    parser.add_argument('output', type=Path)
    parser.add_argument('--from', dest='first', type=date.fromisoformat, required=True)
    parser.add_argument('--to', dest='last', type=date.fromisoformat, required=True)
    args = parser.parse_args()
    if args.first > args.last:
        parser.error('--from must be on or before --to')
    daily, result = study(args.root, args.first, args.last)
    args.output.mkdir(parents=True, exist_ok=True)
    (args.output / 'btc-5m-data-quality.json').write_text(json.dumps(result, indent=2) + '\n', encoding='utf-8')
    with (args.output / 'btc-5m-daily-coverage.csv').open('w', newline='', encoding='utf-8') as file:
        writer = csv.DictWriter(file, fieldnames=list(daily[0]))
        writer.writeheader()
        writer.writerows(daily)


if __name__ == '__main__':
    main()
