"""
Overround Decomposition in European Football Markets
Empirical Analysis of 10,000 Closing Lines (2021-2026)

Applied Probability Institute (sportsbettingmath.org)
Dataset: epl-closing-lines-10k.csv
License: Open Data Commons Attribution License (ODC-By) v1.0
"""

import os
import sys
import csv
from collections import defaultdict

def analyze_dataset(csv_path="epl-closing-lines-10k.csv"):
    if not os.path.exists(csv_path):
        # Check relative to script dir
        script_dir = os.path.dirname(os.path.abspath(__file__))
        alt_path = os.path.join(script_dir, csv_path)
        if os.path.exists(alt_path):
            csv_path = alt_path
        else:
            print(f"Error: Dataset not found at {csv_path}")
            return

    print("=" * 72)
    print("APPLIED PROBABILITY INSTITUTE // EMPIRICAL RESEARCH SUITE")
    print("Study: Overround Decomposition in European Football (EPL 10K Closing Lines)")
    print(f"Source file: {csv_path}")
    print("=" * 72)

    rows = []
    with open(csv_path, mode="r", encoding="utf-8") as f:
        reader = csv.DictReader(f)
        for row in reader:
            rows.append(row)

    total_matches = len(rows)
    print(f"\n[+] Successfully parsed {total_matches:,} closing lines.")

    # 1. Season-by-Season Breakdown
    seasons = defaultdict(list)
    for r in rows:
        seasons[r["Season"]].append(float(r["Overround_pct"]))

    print("\n--- 1. OVERROUND DISTRIBUTION BY SEASON ---")
    print(f"{'Season':<12} | {'Matches':<8} | {'Mean Overround':<16} | {'Min':<8} | {'Max':<8}")
    print("-" * 62)
    
    all_overrounds = []
    for s, ovs in sorted(seasons.items()):
        all_overrounds.extend(ovs)
        mean_ov = sum(ovs) / len(ovs)
        print(f"{s:<12} | {len(ovs):<8} | {mean_ov:>14.2f}% | {min(ovs):>6.2f}% | {max(ovs):>6.2f}%")

    overall_mean = sum(all_overrounds) / len(all_overrounds)
    print("-" * 62)
    print(f"{'OVERALL':<12} | {len(all_overrounds):<8} | {overall_mean:>14.2f}% | {min(all_overrounds):>6.2f}% | {max(all_overrounds):>6.2f}%\n")

    # 2. Multiplicative vs Shin Method Divergence
    # We measure how Shin adjusts probabilities for favorites vs longshots
    favorite_divs = []   # Odds < 1.70
    mid_divs = []        # Odds 1.70 to 3.50
    longshot_divs = []   # Odds > 3.50

    for r in rows:
        for prefix in ["Home", "Draw", "Away"]:
            odds = float(r[f"{prefix}Odds"])
            p_mult = float(r[f"Mult_{prefix}Prob"])
            p_shin = float(r[f"Shin_{prefix}Prob"])
            # delta = Shin - Mult (positive means Shin assigns HIGHER probability than simple proportional normalization)
            delta = p_shin - p_mult

            if odds < 1.70:
                favorite_divs.append(delta)
            elif odds <= 3.50:
                mid_divs.append(delta)
            else:
                longshot_divs.append(delta)

    print("--- 2. SHIN'S METHOD VS MULTIPLICATIVE NORMALIZATION (FLB EFFECT) ---")
    print("Favourite-Longshot Bias Analysis: Delta = (P_Shin - P_Multiplicative)")
    print(f"{'Market Segment':<22} | {'Sample Count':<12} | {'Avg Delta (Shin - Mult)':<24}")
    print("-" * 64)
    print(f"{'Heavy Favorites (<1.70)':<22} | {len(favorite_divs):<12} | {sum(favorite_divs)/len(favorite_divs):>+22.2f}%")
    print(f"{'Mid-range (1.70 - 3.50)':<22} | {len(mid_divs):<12} | {sum(mid_divs)/len(mid_divs):>+22.2f}%")
    print(f"{'Longshots (>3.50)':<22} | {len(longshot_divs):<12} | {sum(longshot_divs)/len(longshot_divs):>+22.2f}%")
    print("-" * 64)
    print("[Insight] Shin's model reveals bookmakers inflate longshot probabilities more aggressively")
    print("          to protect against insider information (z-parameter insider trading risk).\n")

    # 3. Expected Value Impact Simulation
    print("--- 3. EXPECTED VALUE (+EV) IMPACT ON BLIND STAKING ---")
    print("Simulated theoretical return of flat 1-unit staking across all outcomes:")
    loss_rate = (1.0 / (1.0 + (overall_mean / 100.0))) - 1.0
    print(f"  Theoretical Market Return (1 / (1 + Vig)): {loss_rate * 100:.2f}% ROI")
    print(f"  Effective Tax per $100 wagered: ${abs(loss_rate) * 100:.2f}")
    print("=" * 72)
    print("Analysis complete. To reproduce plots, install matplotlib & pandas.")

if __name__ == "__main__":
    path = sys.argv[1] if len(sys.argv) > 1 else "epl-closing-lines-10k.csv"
    analyze_dataset(path)
