"""MSC-P-013 randomized campaign ITT reference. Original MIT example."""
from __future__ import annotations

import csv
import math
from pathlib import Path

DATA = Path(__file__).parents[1] / "datasets" / "msc-p013-campaign-incrementality.csv"


def main() -> None:
    with DATA.open(encoding="utf-8", newline="") as stream:
        rows = {row["group"]: row for row in csv.DictReader(stream)}
    if set(rows) != {"control", "test"}:
        raise ValueError("Expected exactly control and test arms")
    n0, y0 = int(rows["control"]["assigned_units"]), int(rows["control"]["conversions"])
    n1, y1 = int(rows["test"]["assigned_units"]), int(rows["test"]["conversions"])
    if min(n0, n1) <= 0 or not (0 <= y0 <= n0 and 0 <= y1 <= n1):
        raise ValueError("Invalid binomial counts")
    p0, p1 = y0 / n0, y1 / n1
    itt = p1 - p0
    se = math.sqrt(p0 * (1 - p0) / n0 + p1 * (1 - p1) / n1)
    low, high = itt - 1.959963984540054 * se, itt + 1.959963984540054 * se
    lift = itt / p0
    incremental = n1 * itt
    assert math.isclose(itt, 0.015, abs_tol=1e-12)
    assert math.isclose(lift, 0.1875, abs_tol=1e-12)
    assert math.isclose(incremental, 300.0, abs_tol=1e-9)
    print(f"control_rate={p0:.6f}")
    print(f"test_rate={p1:.6f}")
    print(f"itt_pp={100 * itt:.6f}")
    print(f"se_pp={100 * se:.6f}")
    print(f"ci95_pp=[{100 * low:.6f}, {100 * high:.6f}]")
    print(f"relative_lift_pct={100 * lift:.6f}")
    print(f"incremental_test_conversions={incremental:.6f}")


if __name__ == "__main__":
    main()
