"""Original opaque fixture: point samples versus explicit encoded-RGB means.
No Photoshop/Procreate implementation is simulated or claimed.
"""
from pathlib import Path
from PIL import Image, ImageDraw, __version__ as pillow_version
from fractions import Fraction
import json, hashlib, platform

# Standalone copy: regenerate the specimen and measurements beside this file.
OUT = Path(__file__).resolve().parent
OUT.mkdir(parents=True, exist_ok=True)
img = Image.new('RGB', (320,160), (180,120,60))
draw = ImageDraw.Draw(img)
draw.rectangle((160,0,319,159), fill=(30,90,180))
img.putpixel((80,80),(240,210,150))
path = OUT/'point-vs-average.png'
img.save(path)
decoded = Image.open(path).convert('RGB')
hx = lambda rgb: '#'+''.join(f'{c:02X}' for c in rgb)
records = []
for label,x,y in [('Flat control',40,80),('Isolated bright pixel',80,80),('Boundary on warm side',159,80)]:
    item = {'label':label,'xy':[x,y], 'point_rgb':list(decoded.getpixel((x,y))), 'windows':[]}
    item['point_hex']=hx(item['point_rgb'])
    for n in [1,3,5]:
        k=n//2
        pixels=[decoded.getpixel((xx,yy)) for yy in range(y-k,y+k+1) for xx in range(x-k,x+k+1)]
        sums=[sum(p[c] for p in pixels) for c in range(3)]
        means=[Fraction(v,n*n) for v in sums]
        # Explicit positive half-up rounding; no dependence on Python's ties-to-even.
        rounded=[(2*v.numerator+v.denominator)//(2*v.denominator) for v in means]
        item['windows'].append({'width':n,'pixel_count':n*n,'bounds_inclusive':[x-k,y-k,x+k,y+k],
                                'channel_sums':sums,'channel_mean_fractions':[str(v) for v in means],
                                'rounded_rgb':rounded,'hex':hx(rounded),
                                'all_source_pixels':[list(p) for p in pixels]})
    records.append(item)
report={'method':'Unweighted per-channel arithmetic mean of encoded RGB byte values, centered odd square windows. Round positive means half up to an integer. No linear-light conversion, gamma correction, alpha, resampling, JPEG, screenshot or ICC profile.',
        'formula':'mean[channel] = sum(source pixel channel in centered n*n window) / (n*n); integer = floor(mean + 0.5)',
        'scope':'Illustrates explicitly defined sampling operations. Averaged numbers are our calculations, not readings from Photoshop, Procreate, Roblox or the website. The website reads a single decoded pixel.',
        'authored_inputs':{'dimensions':[320,160],'warm_fill':[180,120,60],'cool_fill':[30,90,180],'boundary_x':160,'bright_pixel':{'xy':[80,80],'rgb':[240,210,150]}},
        'python':platform.python_version(),'pillow':pillow_version,'source_file':path.name,
        'sha256':hashlib.sha256(path.read_bytes()).hexdigest(),'bytes':path.stat().st_size,'samples':records}
(OUT/'measurements.json').write_text(json.dumps(report,indent=2),encoding='utf8')
rows=['| Sample (X,Y) | Point | Calculated 3×3 mean | Calculated 5×5 mean |','|---|---|---|---|']
for r in records:
    rows.append(f'| {r["label"]} {tuple(r["xy"])} | {r["windows"][0]["hex"]} | {r["windows"][1]["hex"]} | {r["windows"][2]["hex"]} |')
(OUT/'measurement-table.md').write_text('\n'.join(rows)+'\n',encoding='utf8')
svg=['<svg xmlns="http://www.w3.org/2000/svg" width="900" height="430" viewBox="0 0 900 430"><rect width="900" height="430" fill="#f8fafc"/><style>text{font-family:Arial,sans-serif;fill:#202a39}.small{font-size:15px}.head{font-size:19px;font-weight:bold}</style><text x="28" y="36" class="head">Same file. Different sampling areas.</text><text x="28" y="62" class="small">Opaque original PNG; averages calculated from encoded RGB bytes.</text>']
for x,title in [(295,'Point pixel'),(495,'3×3 mean'),(695,'5×5 mean')]:svg.append(f'<text x="{x}" y="106" class="head">{title}</text>')
for i,r in enumerate(records):
    y=130+i*83
    svg.append(f'<text x="28" y="{y+22}" class="small">{r["label"]}</text><text x="28" y="{y+46}" class="small">X {r["xy"][0]}, Y {r["xy"][1]}</text>')
    for j,w in enumerate(r['windows']):
        x=295+j*200
        svg.append(f'<rect x="{x}" y="{y}" width="150" height="36" rx="4" fill="{w["hex"]}"/><text x="{x}" y="{y+59}" class="small">{w["hex"]}</text>')
svg.append('<text x="28" y="409" class="small">Calculated means are not claimed as any editor’s measured output.</text></svg>')
(OUT/'sampling-comparison.svg').write_text(''.join(svg),encoding='utf8')
print('\n'.join(rows))
