#!/usr/bin/env python3
"""
ESM Open Data Verification Suite
Validates schema conformity, range boundaries, and stochastic axioms across public CS2 datasets.
"""
import csv
import sys
import os

def find_dataset(filename):
    candidates = [
        os.path.join(os.path.dirname(__file__), filename),
        os.path.join(os.path.dirname(__file__), "..", "data", filename),
        os.path.join(os.path.dirname(__file__), "data", filename),
        os.path.join(os.getcwd(), "data", filename),
        os.path.join(os.getcwd(), filename)
    ]
    for c in candidates:
        if os.path.exists(c):
            return c
    return None

def verify_ratings():
    path = find_dataset("cs2_team_ratings_2026.csv")
    if not path or not os.path.exists(path):
        print(f"FAIL: cs2_team_ratings_2026.csv not found")
        return False
    with open(path, "r", encoding="utf-8") as f:
        reader = csv.DictReader(f)
        count = 0
        for row in reader:
            count += 1
            elo = float(row["elo_rating"])
            glicko = float(row["glicko2_rating"])
            rd = float(row["glicko2_rd"])
            vol = float(row["volatility"])
            wr = float(row["win_rate_l90"])
            
            assert 800 <= elo <= 2500, f"Elo out of bounds: {elo}"
            assert 800 <= glicko <= 2500, f"Glicko out of bounds: {glicko}"
            assert 30 <= rd <= 350, f"RD out of bounds: {rd}"
            assert 0.01 <= vol <= 0.15, f"Volatility out of bounds: {vol}"
            assert 0.0 <= wr <= 1.0, f"Win rate out of bounds: {wr}"
        print(f"OK: Verified {count} team rating rows.")
    return True

def verify_map_winrates():
    path = find_dataset("cs2_map_win_rates_2026.csv")
    if not path or not os.path.exists(path):
        print(f"FAIL: cs2_map_win_rates_2026.csv not found")
        return False
    with open(path, "r", encoding="utf-8") as f:
        reader = csv.DictReader(f)
        count = 0
        maps = ["mirage_wr", "inferno_wr", "anubis_wr", "nuke_wr", "ancient_wr", "vertigo_wr", "dust2_wr"]
        for row in reader:
            count += 1
            total_maps = int(row["total_maps_tracked"])
            assert total_maps > 0, f"Invalid total maps: {total_maps}"
            for m in maps:
                val = float(row[m])
                assert 0.0 <= val <= 1.0, f"Invalid winrate {val} on map {m}"
        print(f"OK: Verified {count} team map winrate rows.")
    return True

if __name__ == "__main__":
    r_ok = verify_ratings()
    m_ok = verify_map_winrates()
    if r_ok and m_ok:
        print("ALL DATASETS PASSED EMPIRICAL VERIFICATION (100% INTEGRITY)")
        sys.exit(0)
    else:
        sys.exit(1)
