"""Branch odds for the storefront rule, computed before any storefront is screened.

    python research/agent-storefronts/branches.py > research/agent-storefronts/branches.txt

n = storefronts whose own site publishes a record of sales or payments.
k = those whose record shows at least one sale to an outside party.
Rule (README.md): n < 5 -> inconclusive (coverage); k/n >= 0.5 -> survived;
k/n < 0.25 -> killed; otherwise inconclusive.

Each storefront with a record is treated as an independent draw with true share p.
Two tables: unconditional, and conditional on the three rows seen before sealing
(Cairn: one outside sale seen; Scholium, Tracewake: none), where only the other
n - 3 are random.
"""
from math import comb


def verdict(k, n):
    if n < 5:
        return "inconclusive"
    s = k / n
    if s >= 0.5:
        return "survived"
    if s < 0.25:
        return "killed"
    return "inconclusive"


def table(n, p, known_yes=0, known_no=0):
    free = n - known_yes - known_no
    out = {"survived": 0.0, "killed": 0.0, "inconclusive": 0.0}
    for j in range(free + 1):
        pr = comb(free, j) * p ** j * (1 - p) ** (free - j)
        out[verdict(known_yes + j, n)] += pr
    return out


if __name__ == "__main__":
    for label, ky, kn in (("unconditional", 0, 0), ("given Cairn yes, Scholium no, Tracewake no", 1, 2)):
        print(f"## {label}")
        print("| n with a record | true share p | P(survived) | P(killed) | P(inconclusive) |")
        print("|---|---|---|---|---|")
        for n in (5, 8, 12, 20):
            for p in (0.05, 0.2, 0.35, 0.5, 0.7):
                t = table(n, p, ky, kn)
                print(f"| {n} | {p:.2f} | {t['survived']:.4f} | {t['killed']:.4f} | {t['inconclusive']:.4f} |")
        print()
