"""Replay a single-service TruIndex research scenario. Uses only standard Python."""

import argparse
import json
from collections import Counter, defaultdict
from fractions import Fraction
from pathlib import Path


def count(value, label):
    if type(value) is not int or value < 0:
        raise ValueError(f"{label} must be a nonnegative integer")
    return value


def name(value, label):
    if not isinstance(value, str) or not value.strip():
        raise ValueError(f"{label} needs a nonempty name")
    return value


def benefit(requests, baseline, extra):
    return min(extra, max(0, requests - baseline))


def allocate(budget, rate, credits):
    """Cap each claim, then apportion available whole units by largest remainder."""
    total = sum(credits.values())
    if total == 0:
        return {}
    spend = min(budget, rate * total)
    shares = {who: Fraction(spend * score, total) for who, score in credits.items()}
    awards = {who: int(share) for who, share in shares.items()}
    order = sorted(shares, key=lambda who: (-(shares[who] - awards[who]), who))
    for who in order[:spend - sum(awards.values())]:
        awards[who] += 1
    return awards


def largest_share(balances):
    total = sum(balances.values())
    return str(Fraction(max(balances.values()), total)) if total else None


def replay(scenario):
    balances = dict(scenario["opening_balances"])
    if not balances:
        raise ValueError("at least one account is required")
    for who, amount in balances.items():
        name(who, "account")
        count(amount, "opening balance")
    rate = count(scenario["rate_per_unit"], "rate per unit")
    history = defaultdict(list)
    seen_windows = set()
    periods = []
    for period in scenario["periods"]:
        sponsor = period["sponsor"]
        budget = count(period["budget"], "budget")
        if sponsor not in balances or budget > balances[sponsor]:
            raise ValueError("the sponsor must hold the offered budget")
        credits = Counter()
        missing = False
        observations = []
        results = []
        for window in period["windows"]:
            key = name(window["id"], "window ID")
            if key in seen_windows:
                raise ValueError(f"duplicate window {key}")
            seen_windows.add(key)
            place = name(window["context"], "context")
            baseline = count(window["baseline"], "baseline supply")
            extra = count(window["delivered"], "extra units delivered")
            who = window.get("supplier")
            if extra and who not in balances:
                raise ValueError(f"{key} needs a known supplier")
            past = history[place]
            # Quote the opportunity for ONE additional unit before seeing this period.
            forecast = (Fraction(sum(d > baseline for d in past), len(past))
                        if past else None)
            requests = window["requests"]
            score = None
            if requests is not None:
                requests = count(requests, "requests")
                score = benefit(requests, baseline, extra)
                observations.append((place, requests))
                if score:
                    credits[who] += score
            elif extra:
                missing = True
            results.append({"id": key, "prior_windows": len(past),
                            "next_unit_forecast": str(forecast) if forecast is not None else None,
                            "additional_requests_met": score})
        for place, requests in observations:
            history[place].append(requests)
        # An unknown delivered outcome defers this period's entire settlement.
        awards = {} if missing else allocate(budget, rate, credits)
        paid = sum(awards.values())
        balances[sponsor] -= paid
        for who, award in awards.items():
            balances[who] += award
        periods.append({"period": period["period"], "windows": results,
                        "settlement": "deferred" if missing else "closed",
                        "payouts": awards, "budget_unused": budget - paid,
                        "closing_balances": balances.copy(),
                        "largest_share": largest_share(balances)})
    return {"opening_largest_share": largest_share(scenario["opening_balances"]),
            "periods": periods, "closing_balances": balances}


def show(result):
    print("TruIndex simulation (trial HVT)")
    print("Largest opening share:", result["opening_largest_share"] or "unknown")
    for period in result["periods"]:
        print(f"\n{period['period']}")
        for window in period["windows"]:
            estimate = window["next_unit_forecast"]
            score = window["additional_requests_met"]
            print(f"  {window['id']} | chance one extra unit helps: "
                  f"{estimate if estimate is not None else 'unknown'} "
                  f"({window['prior_windows']} prior windows) | "
                  f"extra requests met: {score if score is not None else 'unknown'}")
        awards = ", ".join(f"{who} {amount}" for who, amount in period["payouts"].items())
        print(f"  Settlement {period['settlement']} | payouts: {awards or 'none'} | "
              f"unused budget: {period['budget_unused']}")
        print("  Largest balance share:", period["largest_share"] or "unknown")
    print("\nClosing balances:", ", ".join(f"{who} {balance}"
          for who, balance in result["closing_balances"].items()))


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("scenario", type=Path, help="scenario JSON file")
    parser.add_argument("--json", action="store_true", help="print machine-readable results")
    args = parser.parse_args()
    try:
        scenario = json.loads(args.scenario.read_text(encoding="utf-8"))
        result = replay(scenario)
        if args.json:
            print(json.dumps(result, indent=2, allow_nan=False))
        else:
            show(result)
    except (OSError, ValueError, TypeError, KeyError) as error:
        raise SystemExit(f"Invalid scenario: {error}") from error
