"""Reproduce Mittalmar's fixed-cohort YouTube reference-shortlist study.

Python 3.9+ and the standard library. Run:
    python3 reproduce.py videos_labeled.csv OUTPUT_DIRECTORY

Input: Gustav Sloth (2025), YouTube Videos With View Count Time Series,
https://doi.org/10.5281/zenodo.14602718 (Creative Commons Attribution 4.0).
Direct CSV: https://zenodo.org/records/14602718/files/videos_labeled.csv
"""

import argparse
import csv
import hashlib
import sys
from collections import Counter, defaultdict
from pathlib import Path
from statistics import median, quantiles

SOURCE_SHA256 = "6e8b8b750100826481d3e1f6169a15ea2b999b90d8eccc6549e8cd7b8357b649"
LAST_DAY = 19
CHECKPOINTS = (1, 3, 7, 14, 19)


def read_videos(path):
    if hashlib.sha256(path.read_bytes()).hexdigest() != SOURCE_SHA256:
        raise ValueError("Input does not match the frozen Zenodo CSV.")
    histories = defaultdict(set)
    counts = Counter()
    with path.open(encoding="utf-8-sig", newline="") as file:
        for row in csv.DictReader(file):
            counts["raw_rows"] += 1
            identifier = row["video_id"]
            duration = float(row["duration"])
            views = tuple(int(row[f"day{day}"]) for day in range(LAST_DAY + 1))
            if not identifier or not duration > 0 or any(v < 0 for v in views):
                raise ValueError("Invalid ID, duration, or negative views.")
            histories[identifier].add((duration, views))

    counts["distinct_ids"] = len(histories)
    videos = {}
    for identifier, variants in histories.items():
        if len(variants) > 1:
            counts["conflicting_ids"] += 1
            continue
        duration, views = next(iter(variants))
        if duration < 240:
            counts["under_four_minutes"] += 1
            continue
        videos[identifier] = views
    counts["included"] = len(videos)
    return videos, counts


def shortlist(videos, day, percent):
    ordered_counts = sorted((views[day] for views in videos.values()), reverse=True)
    target_size = (len(videos) * percent + 99) // 100
    cutoff = ordered_counts[target_size - 1]
    selected = {key for key, views in videos.items() if views[day] >= cutoff}
    return cutoff, selected


def write_overlap(output, videos):
    columns = [
        "analysis", "observation_day", "cohort_size", "shortlist_target_pct",
        "cutoff_views", "shortlisted", "day19_top_decile",
        "day19_top_in_shortlist", "day19_top_missed", "day19_top_coverage_pct",
    ]
    steady = {key: views for key, views in videos.items()
              if all(a <= b for a, b in zip(views, views[1:]))}
    groups = [
        ("checkpoint", videos, [(day, 10) for day in CHECKPOINTS]),
        ("wider_shortlist", videos, [(7, 15), (7, 20)]),
        ("sensitivity_no_daily_decreases", steady, [(7, 10)]),
    ]
    with output.open("w", encoding="utf-8", newline="") as file:
        writer = csv.writer(file, lineterminator="\n")
        writer.writerow(columns)
        for analysis, group, selections in groups:
            _, final = shortlist(group, LAST_DAY, 10)
            for day, percent in selections:
                cutoff, early = shortlist(group, day, percent)
                overlap = len(early & final)
                missed = len(final - early)
                writer.writerow([analysis, day, len(group), percent, cutoff, len(early),
                                 len(final), overlap, missed, f"{100 * overlap / len(final):.4f}"])


def write_shares(output, videos):
    positive = [views for views in videos.values() if views[LAST_DAY] > 0]
    with output.open("w", encoding="utf-8", newline="") as file:
        writer = csv.writer(file, lineterminator="\n")
        writer.writerow(["observation_day", "nonzero_final_count", "share_p25_pct",
                         "share_median_pct", "share_p75_pct"])
        for day in CHECKPOINTS:
            shares = [100 * views[day] / views[LAST_DAY] for views in positive]
            lower, _, upper = quantiles(shares, n=4, method="inclusive")
            writer.writerow([day, len(shares), f"{lower:.4f}", f"{median(shares):.4f}",
                             f"{upper:.4f}"])


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("source", type=Path, help="Zenodo's videos_labeled.csv")
    parser.add_argument("output_directory", type=Path)
    args = parser.parse_args()
    videos, counts = read_videos(args.source)
    args.output_directory.mkdir(parents=True, exist_ok=True)
    write_overlap(args.output_directory / "shortlist-overlap.csv", videos)
    write_shares(args.output_directory / "view-shares.csv", videos)
    print(", ".join(f"{key}={value}" for key, value in counts.items()), file=sys.stderr)


if __name__ == "__main__":
    main()
