from fractions import Fraction
from hashlib import sha256
import json
from pathlib import Path

from PIL import Image, ImageDraw, ExifTags

root = Path(__file__).resolve().parents[4]
out = root / "work" / "site" / "assets" / "photo-metadata"
out.mkdir(parents=True, exist_ok=True)

# A synthetic geometric card is used instead of a portrait or a real location.
im = Image.new("RGB", (1200, 840), "#f1f5f9")
d = ImageDraw.Draw(im)
d.rounded_rectangle((72, 72, 1128, 768), radius=40, fill="#ffffff", outline="#cbd5e1", width=4)
d.rounded_rectangle((120, 136, 1080, 298), radius=28, fill="#dbeafe")
d.text((168, 184), "SYNTHETIC ERAS PHOTO FILE", fill="#1e3a5f", stroke_width=0)
d.rounded_rectangle((120, 344, 552, 694), radius=28, fill="#ecfeff", outline="#0891b2", width=5)
d.rounded_rectangle((648, 344, 1080, 694), radius=28, fill="#fff7ed", outline="#ea580c", width=5)
d.text((164, 408), "PIXELS", fill="#155e75")
d.text((164, 476), "1200 x 840", fill="#155e75")
d.text((692, 408), "METADATA", fill="#9a3412")
d.text((692, 476), "GPS / camera / time", fill="#9a3412")

exif = Image.Exif()
exif[ExifTags.Base.Make] = "Synthetic Test"
exif[ExifTags.Base.Model] = "No real camera"
exif[ExifTags.Base.DateTime] = "2026:10:29 09:00:00"
exif[ExifTags.IFD.GPSInfo] = {
    ExifTags.GPS.GPSLatitudeRef: "N",
    ExifTags.GPS.GPSLatitude: (Fraction(0), Fraction(0), Fraction(0)),
    ExifTags.GPS.GPSLongitudeRef: "E",
    ExifTags.GPS.GPSLongitude: (Fraction(0), Fraction(0), Fraction(0)),
}
source = out / "synthetic-with-gps.jpg"
clean = out / "synthetic-reencoded-without-exif.jpg"
im.save(source, "JPEG", quality=92, exif=exif.tobytes(), optimize=True)

with Image.open(source) as loaded:
    source_size = loaded.size
    source_exif = loaded.getexif()
    source_gps = source_exif.get_ifd(ExifTags.IFD.GPSInfo)
    decoded = loaded.convert("RGB")
    source_pixel_hash = sha256(decoded.tobytes()).hexdigest()
    # Re-encode decoded pixels without passing EXIF data.
    decoded.save(clean, "JPEG", quality=92, optimize=True)

with Image.open(clean) as loaded:
    clean_size = loaded.size
    clean_exif = loaded.getexif()
    clean_gps = clean_exif.get_ifd(ExifTags.IFD.GPSInfo)
    clean_pixel_hash = sha256(loaded.convert("RGB").tobytes()).hexdigest()

def entry(path, size, exif_data, gps_data, pixel_hash):
    return {
        "file": path.name,
        "bytes": path.stat().st_size,
        "dimensions_px": list(size),
        "exif_tags": {str(k): str(v) for k, v in exif_data.items() if k != ExifTags.IFD.GPSInfo},
        "gps_ifd": {str(k): str(v) for k, v in gps_data.items()},
        "decoded_rgb_sha256": pixel_hash,
        "sha256": sha256(path.read_bytes()).hexdigest(),
    }

result = {
    "created_at_local": "2026-10-29 Asia/Shanghai",
    "method": "Create one synthetic 1200x840 geometric JPEG with dummy GPS (0 N, 0 E), camera-label and date tags; inspect EXIF; decode/re-encode at the same JPEG quality without carrying EXIF; inspect again.",
    "safety": "No portrait, real camera, or real location was used; dummy GPS is 0,0.",
    "files": [entry(source, source_size, source_exif, source_gps, source_pixel_hash), entry(clean, clean_size, clean_exif, clean_gps, clean_pixel_hash)],
    "observations": {
        "dimensions_preserved": source_size == clean_size,
        "gps_removed_in_reencoded_output": not bool(clean_gps),
        "camera_and_datetime_tags_removed": not any(k in clean_exif for k in (ExifTags.Base.Make, ExifTags.Base.Model, ExifTags.Base.DateTime)),
        "decoded_pixel_hash_equal": source_pixel_hash == clean_pixel_hash,
        "interpretation": "This demonstrates behavior for these locally generated files and this Pillow re-encode only. It does not show whether MyERAS, MyIntealth, or another service strips, stores, exposes, or preserves metadata. Re-encoding JPEG can alter decoded pixels even when dimensions remain the same.",
    },
}
(out / "measurements.json").write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
print(json.dumps(result, indent=2))
