"""Reproduce descriptive diagnostics from the frozen v1.1 tables.

Run from any directory with Python 3.10 or newer. JSON is written to stdout.
"""

from collections import Counter
import csv
from dataclasses import dataclass
from decimal import Decimal
import hashlib
import json
from pathlib import Path
from statistics import mean, median


ROOT = Path(__file__).resolve().parents[1]
RELEASE = ROOT / "publish/paper/release-2026-10-20/data"
PHASE4 = ROOT / "data/phase4"
PRIOR = ROOT / "data/processed/league_seasons.csv"
CROSSWALK = ROOT / "data/processed/id_crosswalk.csv"
ROOKIE = "draft_class_rookie"
VETERAN = "veteran"

# Archived price name: (official NBA ID, prior-season table name, NBA identity link).
VETERAN_ALIASES = {
    "Alexandre Sarr": ("1642259", "Alex Sarr", "https://www.nba.com/player/1642259/alexandre-sarr"),
    "Nicolas Claxton": ("1629651", "Nic Claxton", "https://www.nba.com/nets/player/1629651/nicolas-claxton"),
    "Carlton Carrington": ("1642267", "Bub Carrington", "https://www.nba.com/player/1642267/carlton-carrington/profile"),
    "Ron Holland II": ("1641842", "Ron Holland", "https://www.nba.com/player/1641842/ron-holland"),
}
VETERAN_NONPARTICIPANTS = {
    "Malik Beasley": ("1627736", "https://www.nba.com/player/1627736/malik-beasley"),
    "Jared Butler": ("1630215", "https://www.nba.com/player/1630215/jared-butler/profile"),
    "Kyrie Irving": ("202681", "https://www.nba.com/player/202681/kyrie-irving"),
    "Ben Simmons": ("1627732", "https://www.nba.com/player/1627732/ben-simmons"),
    "Jordan Nwora": ("1629670", "https://www.nba.com/player/1629670/jordan-nwora"),
    "Keon Johnson": ("1630553", "https://www.nba.com/stats/player/1630553/traditional"),
    "Jaden Springer": ("1630531", "https://www.nba.com/player/1630531/jaden-springer"),
    "Fred VanVleet": ("1627832", "https://www.nba.com/player/1627832/fred-vanvleet"),
}
PRIOR_DRAFTEES = {
    "Nikola Topic": ("1642260", "https://www.nba.com/player/1642260"),
    "DaRon Holmes II": ("1641747", "https://www.nba.com/player/1641747/daron-holmes-ii"),
}


@dataclass(frozen=True)
class MarketPlayer:
    year: int
    group: str
    adp: Decimal
    band: str
    actual_fp: float
    surplus: float


def read_csv(path):
    with path.open(newline="", encoding="utf-8") as stream:
        return list(csv.DictReader(stream))


def market_player(row):
    return MarketPlayer(
        int(row["season_start_year"]), row["group"], Decimal(row["espn_adp"]),
        row["adp_band"], float(row["actual_fp_adj"]), float(row["fp_surplus"]),
    )


def resolve_2025(source_rows, league, prior, crosswalk, yang, scale):
    """Keep the published inputs intact and return separate verified additions."""
    unresolved = {row["source_player_name"]: row for row in source_rows if row["group"] == "unresolved"}
    assert set(unresolved) == set(VETERAN_ALIASES) | set(VETERAN_NONPARTICIPANTS) | set(PRIOR_DRAFTEES) | {"Hansen Yang"}
    prior_bbref_ids = {row["bbref_id"] for row in prior}
    assert all(
        player_id in league and crosswalk[player_id]["draft_year"] == "2024"
        and crosswalk[player_id]["bbref_id"] not in prior_bbref_ids
        for player_id, _ in PRIOR_DRAFTEES.values()
    )
    rookie_row = unresolved["Hansen Yang"]
    assert float(rookie_row["espn_adp"]) == float(yang["fantasy_adp"])
    assert league[yang["nba_person_id"]]["team"] == rookie_row["source_team"]
    rookie = market_player(dict(
        rookie_row, group=ROOKIE, actual_fp_adj=yang["fp_y1_adj"], fp_surplus=yang["fp_surplus"],
    ))
    participating, zeros, identities = [], [], []
    for name, (player_id, prior_name, link) in VETERAN_ALIASES.items():
        outcome = league[player_id]
        assert outcome["team"] == unresolved[name]["source_team"]
        actual = float(outcome["fp_total"]) * scale
        participating.append(resolved_veteran(unresolved[name], actual))
        identities.append(identity(unresolved[name], prior_name, link, player_id, prior, outcome["player_name"], actual))
    for name, (player_id, link) in VETERAN_NONPARTICIPANTS.items():
        assert player_id not in league
        assert unresolved[name]["source_name_has_unique_prior_nba_appearance"] == "True"
        zeros.append(resolved_veteran(unresolved[name], 0))
        identities.append(identity(unresolved[name], name, link, player_id, prior, None, 0))
    return rookie, participating, zeros, identities


def resolved_veteran(row, actual):
    return market_player(dict(
        row, group=VETERAN, actual_fp_adj=actual,
        fp_surplus=actual - float(row["market_implied_fp_adj"]),
    ))


def identity(source_row, prior_name, link, player_id, prior, league_name, actual):
    latest = max((row for row in prior if row["player_name"] == prior_name),
                 key=lambda row: int(row["season_start_year"]))
    return {
        "archive_name": source_row["source_player_name"], "archive_url": source_row["source_url"],
        "adp": float(source_row["espn_adp"]), "nba_person_id": player_id, "nba_identity_source": link,
        "latest_prior_season_in_table": latest["season"], "prior_name": prior_name,
        "prior_bbref_id": latest["bbref_id"],
        "prior_gp": int(float(latest["gp"])), "current_league_name": league_name,
        "outcome": "matched_participant" if league_name else "verified_regular_season_nonparticipant",
        "adjusted_points": round(actual, 4),
    }


def contrast(rows):
    rookies = [r for r in rows if r.group == ROOKIE]
    veterans = [r for r in rows if r.group == VETERAN]
    broad_gaps, close_gaps, adp_distances = [], [], []
    broad_vets, close_vets = set(), set()
    for r in rookies:
        same_year = [(i, v) for i, v in enumerate(veterans) if v.year == r.year]
        band = [(i, v) for i, v in same_year if v.band == r.band]
        close = [(i, v) for i, v in same_year if abs(r.adp - v.adp) <= 5]
        if band:
            broad_vets.update(i for i, _ in band)
            broad_gaps.append(r.surplus - mean(v.surplus for _, v in band))
        if close:
            close_vets.update(i for i, _ in close)
            close_gaps.append(r.actual_fp - mean(v.actual_fp for _, v in close))
            adp_distances.append(mean(abs(r.adp - v.adp) for _, v in close))
    return {
        "priced_rookies": len(rookies), "priced_veterans": len(veterans),
        "broad_band": {
            "supported_rookies": len(broad_gaps), "supported_veterans": len(broad_vets),
            "rookie_minus_veteran_surplus": round(mean(broad_gaps), 4),
        },
        "within_five_adp": {
            "supported_rookies": len(close_gaps), "supported_veterans": len(close_vets),
            "rookie_minus_veteran_points": round(mean(close_gaps), 4),
            "mean_absolute_adp_distance": float(round(mean(adp_distances), 4)),
        },
    }


def selection(board, corrected_prices):
    priced_picks = {int(r["overall_pick"]) for r in corrected_prices}
    groups = {}
    for label, priced in (("priced", True), ("unpriced", False)):
        rows = [r for r in board if (int(r["overall_pick"]) in priced_picks) == priced]
        groups[label] = {
            "n": len(rows), "mean_adjusted_points": round(mean(float(r["actual_fp_adj"]) for r in rows), 4),
            "median_nba_pick": median(int(r["overall_pick"]) for r in rows),
            "nonparticipants": sum(float(r["gp_y1"]) == 0 for r in rows),
        }
    groups["priced_at_adp_139_or_later"] = sum(float(r["fantasy_adp"]) >= 139 for r in corrected_prices)
    rounds = {}
    for name, low, high in (("first_round", 1, 30), ("second_round", 31, 59)):
        rows = [r for r in board if low <= int(r["overall_pick"]) <= high]
        coverage = {}
        for model in ("m3", "m0"):
            covered = sum(
                float(r[f"frozen_{model}_interval_lower"]) <= float(r["actual_fp_adj"])
                <= float(r[f"frozen_{model}_interval_upper"]) for r in rows
            )
            coverage[model] = {"covered": covered, "fraction": round(covered / len(rows), 6)}
        rounds[name] = {
            "picks": len(rows), "priced": sum(int(r["overall_pick"]) in priced_picks for r in rows),
            "nominal_80_percent_interval_coverage": coverage,
        }
    return groups, rounds


def main():
    modern_path = RELEASE / "market_matched_modern_players.csv"
    legacy_path = RELEASE / "market_matched_legacy_players.csv"
    raw_path = RELEASE / "market_all_source_rows_modern.csv"
    prices_path = RELEASE / "market_reviewed_alias_sensitivity20.csv"
    board_path = RELEASE / "model_all59_reproducibility.csv"
    league_path = PHASE4 / "league2025_26.csv"
    manifest_path = PHASE4 / "manifest.json"
    manifest = json.loads(manifest_path.read_text())
    paths = [modern_path, legacy_path, raw_path, prices_path, board_path, league_path, manifest_path, PRIOR, CROSSWALK]
    hashes = {str(p.relative_to(ROOT)): hashlib.sha256(p.read_bytes()).hexdigest() for p in paths}
    assert hashes[str(league_path.relative_to(ROOT))] == manifest["output_sha256"]["league"]
    assert manifest["collection_complete"] and manifest["league_summary"]["complete_totals"]
    league_rows = read_csv(league_path)
    league = {r["nba_person_id"]: r for r in league_rows}
    assert len(league) == len(league_rows) == manifest["league_summary"]["player_count"] == 582
    assert all(player_id and float(row["gp"]) > 0 for player_id, row in league.items())

    modern = [market_player(row) for row in read_csv(modern_path)]
    legacy = [market_player(row) for row in read_csv(legacy_path)]
    source_2025 = [r for r in read_csv(raw_path) if r["season_start_year"] == "2025" and r["espn_adp"]]
    prices = read_csv(prices_path)
    yang = next(r for r in prices if r["reviewed_alias_adp_separate_from_original"])
    prior = [r for r in read_csv(PRIOR) if float(r["gp"]) > 0]
    crosswalk = {r["nba_person_id"]: r for r in read_csv(CROSSWALK) if r["nba_person_id"]}
    rookie, participating, zeros, identities = resolve_2025(
        source_2025, league, prior, crosswalk, yang, manifest["S_ref"] / manifest["S_test"],
    )
    corrected = modern + [rookie] + participating + zeros
    sample_counts = Counter(r.group for r in corrected if r.year == 2025)
    assert sample_counts[ROOKIE] == len(prices) == 20
    assert len(source_2025) == sum(sample_counts.values()) + len(PRIOR_DRAFTEES) == 299
    groups, rounds = selection(read_csv(board_path), prices)
    samples = {
        "original_v1_1": modern, "corrected_rookie_only": modern + [rookie],
        "corrected_participating_veterans": modern + [rookie] + participating,
        "corrected_all_priced_veterans": corrected,
    }
    output = {
        "status": "Exploratory descriptive reanalysis of locked outcomes and archived ADP.",
        "definitions": {
            "broad_band": "Same-season prior-curve surplus differences within the v1.1 ADP bands, weighting each rookie equally.",
            "within_five_adp": "Each rookie's observed adjusted points minus the mean for same-season veterans within five numeric ESPN ADP spots. Each supported rookie has equal weight. Veterans can be reused.",
            "verified_zero": "An official NBA ID with prior regular-season appearances is absent from the validated complete 2025–26 regular-season NBA participant table.",
            "limits": "The identity corrections apply only to 2025. Earlier seasons use the original matched-participant tables. Comparisons use observed archived prices and remain descriptive, with no causal or future-class inference.",
        },
        "sha256_by_input": hashes,
        "numeric_price_rows_2025": {
            "total": len(source_2025), "draft_class_rookies": sample_counts[ROOKIE],
            "participating_veterans": sample_counts[VETERAN] - len(zeros),
            "nonparticipating_veterans": len(zeros),
            "prior_draftees_without_prior_appearance": {
                name: {"nba_person_id": player_id, "nba_identity_source": link}
                for name, (player_id, link) in PRIOR_DRAFTEES.items()
            },
        },
        "recovered_rookie": {
            "archive_name": "Hansen Yang", "league_name": yang["player_name"],
            "nba_person_id": yang["nba_person_id"], "adp": float(rookie.adp), "archive_url": yang["source_url"],
            "nba_identity_source": "https://www.nba.com/blazers/news/trail-blazers-acquire-draft-rights-to-yang-hansen",
        },
        "recovered_veterans": identities,
        "modern_sensitivity": {
            name: {"2025": contrast([r for r in rows if r.year == 2025]), "all_four_classes": contrast(rows)}
            for name, rows in samples.items()
        },
        "modern_by_class_corrected": {
            year: contrast([r for r in corrected if r.year == year]) for year in (2021, 2022, 2023, 2025)
        },
        "modern_excluding_2025": contrast([r for r in corrected if r.year != 2025]),
        "legacy_2013_through_2017": contrast(legacy),
        "observed_adp_selection_2025": groups,
        "coverage_and_price_presence_by_nba_draft_round_2025": rounds,
    }
    print(json.dumps(output, indent=2, ensure_ascii=False))


if __name__ == "__main__":
    main()
