import json, math, sys
R = json.load(open('/tmp/smol-bench/results24.json'))
def curve(img, tool, fmt): return sorted([r for r in R if r['image']==img and r['tool']==tool and r['format']==fmt], key=lambda r: r['bytes'])
def at(img, tool, fmt, metric, target):
    c = curve(img, tool, fmt)
    for a, b in zip(c, c[1:]):
        if a[metric] <= target <= b[metric] and b[metric] > a[metric]:
            t = (target - a[metric]) / (b[metric] - a[metric])
            return math.exp(math.log(a['bytes']) + t * (math.log(b['bytes']) - math.log(a['bytes'])))
    return None
def table(images, series, metric, targets):
    out = {}
    for target in targets:
        print(f"\n== total bytes over {len(images)} images to reach {metric} = {target}")
        for tool, fmt in series:
            vals = [at(i, tool, fmt, metric, target) for i in images]
            miss = sum(v is None for v in vals)
            if miss: print(f"  {tool:8} {fmt:5}  unreachable on {miss} of {len(images)} images"); continue
            out[(target, tool, fmt)] = round(sum(vals)); print(f"  {tool:8} {fmt:5}  {round(sum(vals)):>10,}")
    return out
ALL = [f"kodim{i:02d}" for i in range(1, 25)]
series = [('Smol','avif'),('sips','avif'),('Smol','webp'),('Caesium','webp'),('Smol','jpeg'),('sips','jpeg'),('Caesium','jpeg')]
table(ALL, series, 'ssimulacra2', (65, 70, 75, 80, 85))
table(ALL, series, 'ssim', (0.93, 0.94, 0.95, 0.96))
print("\n#### three-image subset with Zipic")
table(['kodim07','kodim08','kodim23'], series[:0] + [('Smol','jpeg'),('Zipic','jpeg'),('sips','jpeg'),('Caesium','jpeg')], 'ssimulacra2', (70, 75))
print("\n#### fixed-setting totals over 24 images (bytes, mean SSIM, mean SSIMULACRA2)")
import collections
agg = collections.defaultdict(list)
for r in R: agg[(r['tool'], r['format'], str(r['setting']))].append(r)
for k in sorted(agg):
    v = agg[k]
    print(f"  {k[0]:8} {k[1]:5} {k[2]:14} n={len(v):2}  {sum(x['bytes'] for x in v):>10,}  ssim {sum(x['ssim'] for x in v)/len(v):.4f}  s2 {sum(x['ssimulacra2'] for x in v)/len(v):6.2f}")
