"""Original, deterministic PNG/JPEG fixture. No downloaded images or color profiles."""
from pathlib import Path
from PIL import Image, ImageDraw, __version__ as pillow_version, features
import numpy as np
import json, hashlib, platform, shutil

ROOT = Path(__file__).resolve().parents[2]
ASSETS = Path(__file__).resolve().parent if Path(__file__).name == 'reproduce.py' else ROOT / 'outputs/color-picker-from-image/assets/png-jpeg-test'
ASSETS.mkdir(parents=True, exist_ok=True)
img = Image.new('RGB', (192,128), '#2463EB')
d = ImageDraw.Draw(img)
d.rectangle((95,0,191,127), fill='#F47B52')
d.rectangle((20,80,70,110), fill='#F8FAFC')
d.line((0,64,191,64), fill='#212936', width=1)
img.save(ASSETS/'reference.png')
points = [('Blue center',40,30),('Blue edge',94,30),('Orange edge',95,30),('Orange center',150,30),('Fine dark line',40,64),('Light patch',40,95)]
base = np.asarray(img).astype(np.int16)
results = []
def hx(v): return '#' + ''.join(f'{int(x):02X}' for x in v)
for name, quality in [('reference.png',None),('jpeg-q95.jpg',95),('jpeg-q60.jpg',60)]:
    if quality is not None: img.save(ASSETS/name,quality=quality,subsampling=2)
    decoded = Image.open(ASSETS/name).convert('RGB')
    a = np.asarray(decoded).astype(np.int16)
    diff = np.abs(a-base)
    changed = int(np.any(diff!=0,axis=2).sum())
    results.append({'file':name,'quality':quality,'subsampling': '4:2:0' if quality else None,
       'sha256':hashlib.sha256((ASSETS/name).read_bytes()).hexdigest(),
       'bytes':(ASSETS/name).stat().st_size,'total_pixels':192*128,'changed_pixels':changed,
       'changed_percent':round(100*changed/(192*128),4),'mae_per_channel':round(float(diff.mean()),6),
       'max_channel_error':int(diff.max()),
       'samples':[{'label':label,'x':x,'y':y,'rgb':[int(z) for z in a[y,x]],'hex':hx(a[y,x])} for label,x,y in points]})
    decoded.crop((87,22,103,38)).resize((512,512),Image.Resampling.NEAREST).save(ASSETS/(name.split('.')[0]+'-edge.png'))
report={'method':'Pillow RGB fixture; 192x128; JPEG quality 95/60 and subsampling=2; no ICC; no resize; decode with Pillow; coordinates zero-based; compare against reference RGB values',
        'pillow':pillow_version,'jpeg_codec':features.version_codec('jpg'),'python':platform.python_version(),
        'changed_formula':'100 * count(any(decoded RGB != reference RGB)) / (192 * 128)',
        'mae_formula':'sum(abs(decoded RGB - reference RGB)) / (192 * 128 * 3)',
        'results':results}
(ASSETS/'results.json').write_text(json.dumps(report,indent=2),encoding='utf-8')
if Path(__file__).resolve() != (ASSETS/'reproduce.py').resolve():
    shutil.copy2(__file__,ASSETS/'reproduce.py')
print(json.dumps(report,indent=2))
