#!/usr/bin/env python3
"""Reproduce the Persistfolio Historical Cohort 2004-vs-2025 membership count.

Usage:
  python cohort_membership_check.py /path/to/unzipped/full/release

Reads membership_periods.csv from the purchased Historical Cohort Release 1.1.
The free sample is a subset and will NOT reproduce the 500/223/277 headline.

Counts compare stable Persistfolio security IDs, NOT companies that survived,
bankruptcies, investment returns, or unbroken index tenure. Dates are the
release's reconstructed membership boundaries, not necessarily official
index-effective dates. No historical prices or ticker history are included.
"""
import argparse
import csv
from pathlib import Path


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("release_folder", type=Path)
    args = parser.parse_args()

    path = args.release_folder / "membership_periods.csv"
    with path.open(newline="", encoding="utf-8-sig") as f:
        rows = list(csv.DictReader(f))

    beginning = {
        r["security_id"] for r in rows
        if r["membership_start_date"] == "2004-09-30"
        and r["membership_start_basis"] == "ANCHOR_START"
    }
    represented_at_cutoff = {
        r["security_id"] for r in rows
        if r["membership_end_basis"] == "STILL_ACTIVE_AT_CUTOFF"
        and not r["membership_end_date"]
    }
    if not beginning:
        parser.error("No 2004-09-30 anchor records found in membership_periods.csv")

    still = len(beginning & represented_at_cutoff)
    absent = len(beginning - represented_at_cutoff)
    print(f"September 30, 2004 starting IDs: {len(beginning)}")
    print(f"Still represented September 30, 2025: {still}")
    print(f"No open membership period at cutoff: {absent}")
    print(f"Share without open period: {absent / len(beginning):.1%}")


if __name__ == "__main__":
    main()
