# Every computed number on the engagement-rate guide. Exact fractions, rounded half up to 2 decimals.
from fractions import Fraction as F
from decimal import Decimal, ROUND_HALF_UP
def pct(n, d):
    return str((Decimal(n) * 100 / Decimal(d)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)) + "%"
def pct_f(fr):
    return str((Decimal(fr.numerator) * 100 / Decimal(fr.denominator)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)) + "%"

likes, comments, shares, saves = 420, 35, 20, 25
eng = likes + comments + shares + saves
print("A1 engagements =", eng)
followers, reach, views = 10000, 4000, 8000
print("A2 by followers", pct(eng, followers), "| by reach", pct(eng, reach), "| by views", pct(eng, views))
print("A3 check views >= reach:", views >= reach, "so rate by views <= rate by reach:", F(eng, views) <= F(eng, reach))
print("B1 likes only / followers", pct(likes, followers), "| likes+comments / followers", pct(likes + comments, followers), "| all four / followers", pct(eng, followers))
for fl in (1000, 10000, 100000):
    print("C1 same", eng, "engagements at", fl, "followers =", pct(eng, fl))
# average of per-post rates vs pooled
a_e, a_v = 100, 1000
b_e, b_v = 900, 100000
ra, rb = F(a_e, a_v), F(b_e, b_v)
print("D1 post A", pct(a_e, a_v), "| post B", pct(b_e, b_v))
print("D2 mean of the two rates", pct_f((ra + rb) / 2), "| pooled", pct(a_e + b_e, a_v + b_v), "| pooled engagements", a_e + b_e, "views", a_v + b_v)
# Instagram: interactions vs accounts engaged (hypothetical numbers for the explanation)
inter, accts, viewers = 120, 80, 2000
print("E1 interactions/viewers", pct(inter, viewers), "| accounts engaged/viewers", pct(accts, viewers))
# test-case sanity
print("F1 201 engagements / 20000 followers exact =", Decimal(201) * 100 / Decimal(20000), "-> half up", pct(201, 20000))
print("F2 150/8000 exact =", Decimal(150) * 100 / Decimal(8000), "-> half up", pct(150, 8000))
print("G1 spread between likes only and all four interactions, in percentage points:", Decimal("5.00") - Decimal("4.20"))
print("G2 post B audience / post A audience:", b_v // a_v, "times")
print("G3 difference between exact and tool rounding on the tie case, in percentage points:", Decimal("1.01") - Decimal("1.00"))
