#!/usr/bin/env python3
"""Independent verifier for the article's constructed straddle/SPR ledger."""

import json
from fractions import Fraction
from pathlib import Path


ROOT = Path(__file__).resolve().parents[2]
DATA_PATH = ROOT / "public" / "data" / "poker-straddle-spr-cases.json"


def state(sb, bb, stack, open_to, straddle=0):
    pot = sb + bb + straddle + 2 * open_to
    behind = stack - open_to
    return {
        "flopPot": pot,
        "effectiveStackBehind": behind,
        "flopSpr": round(behind / pot, 4),
        "startingDepthInLargestLiveBlind": round(stack / (straddle or bb), 4),
    }


def main():
    evidence = json.loads(DATA_PATH.read_text(encoding="utf-8"))
    printed = evidence["workedComparison"]
    no_inputs = printed["noStraddle"]
    straddle_inputs = printed["utgStraddle"]
    expected_no = state(
        no_inputs["smallBlind"], no_inputs["bigBlind"],
        no_inputs["effectiveStartingStack"], no_inputs["openTo"],
        no_inputs["straddle"],
    )
    expected_straddle = state(
        straddle_inputs["smallBlind"], straddle_inputs["bigBlind"],
        straddle_inputs["effectiveStartingStack"], straddle_inputs["openTo"],
        straddle_inputs["straddle"],
    )

    for key, expected in (("noStraddle", expected_no), ("utgStraddle", expected_straddle)):
        for field, value in expected.items():
            assert printed[key][field] == value, (key, field, printed[key][field], value)

    no_spr_exact = Fraction(expected_no["effectiveStackBehind"], expected_no["flopPot"])
    straddle_spr_exact = Fraction(
        expected_straddle["effectiveStackBehind"], expected_straddle["flopPot"]
    )
    ratio_exact = straddle_spr_exact / no_spr_exact
    ratio = round(float(ratio_exact), 4)
    assert printed["sprRatioStraddledToUnstraddled"] == ratio == 0.4765
    assert printed["exactFractions"] == {
        "noStraddleSpr": f'{expected_no["effectiveStackBehind"]}/{expected_no["flopPot"]}',
        "utgStraddleSpr": f'{expected_straddle["effectiveStackBehind"]}/{expected_straddle["flopPot"]}',
        "sprRatioStraddledToUnstraddled": f"{ratio_exact.numerator}/{ratio_exact.denominator}",
    }
    assert len(evidence["ruleProfiles"]) == 3
    assert evidence["effectiveDepthConversions"][-1]["depthInStraddleUnits"] == 50
    print("poker-straddle-spr independent verification passed")


if __name__ == "__main__":
    main()
