#!/usr/bin/env python3
"""Re-runs the check behind dataset.json for google-photos-vs-icloud.

  python3 check.py            rebuild the test photos, check the recorded downloads,
                              re-read every cited page
  python3 check.py --recheck  re-read the cited pages only

The test photos are rebuilt the way they were made on 25 October 2026: the NASA
source photo is downloaded with curl, cropped and resized with macOS `sips`, and its
metadata is replaced with `exiftool`. Both tools must be on PATH (macOS only, for
sips). Their SHA-256 must equal the hashes recorded in dataset.json.

The Google Photos uploads needed a signed-in account and were deleted after the
measurement, so that leg is not re-run: its recorded downloads are checked for
consistency with each other and with the rebuilt inputs, and reported as RECORDED.

Viallo's code rows are re-read only when this script sits inside the Viallo
repository; elsewhere they are reported as RECORDED.

Exit 0 when everything holds, 1 otherwise. Python standard library only.
"""

import csv
import hashlib
import html
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
import urllib.request

HERE = os.path.dirname(os.path.abspath(__file__))
DATASET = os.path.join(HERE, 'dataset.json')
CSV = os.path.join(HERE, 'dataset.csv')
UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)'

EXIF_TAGS = [
    '-Make=Apple', '-Model=iPhone 15 Pro', '-Software=18.0',
    '-LensModel=iPhone 15 Pro back triple camera 6.765mm f/1.78',
    '-DateTimeOriginal=2026:10:25 09:30:00', '-CreateDate=2026:10:25 09:30:00',
    '-OffsetTimeOriginal=-04:00',
    '-GPSLatitude=28.586', '-GPSLatitudeRef=N', '-GPSLongitude=80.651', '-GPSLongitudeRef=W',
    '-GPSAltitude=3', '-GPSAltitudeRef=0',
    '-ExposureTime=1/120', '-FNumber=1.78', '-ISO=80', '-Orientation#=1',
]

failures = []


def report(status, label, detail=''):
    print('%-12s %s%s' % (status, label, (': ' + detail) if detail else ''))
    if status == 'FAIL':
        failures.append('%s: %s' % (label, detail))


# ---------------------------------------------------------------------- pages

def fetch(url):
    req = urllib.request.Request(url, headers={'User-Agent': UA, 'Accept-Language': 'en-US,en;q=0.9'})
    with urllib.request.urlopen(req, timeout=90) as resp:
        charset = resp.headers.get_content_charset() or 'utf-8'
        return resp.read().decode(charset, 'replace')


def normalise(text):
    text = html.unescape(text)
    for a, b in (('‘', "'"), ('’', "'"), ('“', '"'), ('”', '"'),
                 (' ', ' '), ('​', ''), ('…', '...')):
        text = text.replace(a, b)
    text = re.sub('[‐-―−]', '-', text)
    return re.sub(r'\s+', ' ', text).strip().lower()


_pages = {}


def page_text(url):
    if url not in _pages:
        try:
            raw = fetch(url)
            raw = re.sub(r'(?is)<(script|style|noscript)[^>]*>.*?</\1>', ' ', raw)
            _pages[url] = normalise(re.sub(r'(?s)<[^>]+>', ' ', raw))
        except Exception as exc:  # an unreadable page is a failed check, not a crash
            _pages[url] = exc
    return _pages[url]


def check_page(row, label):
    text = page_text(row['url'])
    if isinstance(text, Exception):
        report('FAIL', label, 'page not read (%s)' % text)
    elif normalise(row['quote']) in text:
        report('OK', label)
    else:
        report('FAIL', label, 'quote gone from %s' % row['url'])


def check_record(row, label):
    try:
        doc = json.loads(fetch(row['url']))
    except Exception as exc:
        report('FAIL', label, 'record not read (%s)' % exc)
        return
    for path, want in row['expect']:
        node = doc
        try:
            for step in path:
                node = node[step]
        except (KeyError, IndexError, TypeError):
            report('FAIL', label, '%s missing' % '.'.join(map(str, path)))
            return
        if node != want:
            report('FAIL', label, '%s is %r, recorded %r' % ('.'.join(map(str, path)), node, want))
            return
    report('OK', label)


# ----------------------------------------------------------------------- code

def repo_root():
    path = HERE
    while path != os.path.dirname(path):
        if os.path.exists(os.path.join(path, 'packages', 'shared', 'src', 'config.ts')):
            return path
        path = os.path.dirname(path)
    return None


def check_code(row, label, root):
    if root is None:
        report('RECORDED', label, 'not inside the Viallo repository')
        return
    try:
        with open(os.path.join(root, row['path']), encoding='utf-8') as fh:
            source = fh.read()
    except OSError as exc:
        report('FAIL', label, str(exc))
        return
    if row['quote'] in source:
        report('OK', label)
    else:
        report('FAIL', label, 'line gone from %s' % row['path'])


# ------------------------------------------------------------- the test photos

def sha256(path):
    h = hashlib.sha256()
    with open(path, 'rb') as fh:
        for chunk in iter(lambda: fh.read(1 << 20), b''):
            h.update(chunk)
    return h.hexdigest()


def run(*cmd, cwd):
    subprocess.run(cmd, cwd=cwd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)


def rebuild_inputs(dataset):
    for tool in ('sips', 'exiftool', 'curl'):
        if shutil.which(tool) is None:
            report('FAIL', 'test photos', '%s is not on PATH' % tool)
            return
    work = tempfile.mkdtemp(prefix='gp-vs-icloud-')
    try:
        run('curl', '-sf', '-o', 'src.jpg', dataset['inputs']['source_photo'], cwd=work)
        run('sips', '-c', '5120', '3840', 'src.jpg', '--out', 'crop.jpg', cwd=work)
        run('sips', '-z', '4032', '3024', '-s', 'formatOptions', '90', 'crop.jpg', '--out', 'photo-12mp.jpg', cwd=work)
        run('sips', '-z', '8064', '6048', '-s', 'format', 'heic', 'crop.jpg', '--out', 'photo-48mp.heic', cwd=work)
        for name in ('photo-12mp.jpg', 'photo-48mp.heic'):
            run('exiftool', '-q', '-overwrite_original', '-all=', name, cwd=work)
            run('exiftool', '-q', '-overwrite_original', *EXIF_TAGS, name, cwd=work)
            stem, ext = name.rsplit('.', 1)
            copy = '%s-s.%s' % (stem, ext)
            shutil.copyfile(os.path.join(work, name), os.path.join(work, copy))
            run('exiftool', '-q', '-overwrite_original', '-XMP-dc:Description=storage saver copy', copy, cwd=work)
        for name, rec in dataset['inputs']['files'].items():
            got = sha256(os.path.join(work, name))
            if got == rec['sha256']:
                report('OK', 'rebuilt %s' % name, 'sha256 %s...' % got[:16])
            else:
                report('FAIL', 'rebuilt %s' % name, 'sha256 %s, recorded %s' % (got, rec['sha256']))
    except subprocess.CalledProcessError as exc:
        report('FAIL', 'test photos', '%s failed: %s' % (exc.cmd[0], exc.stderr.decode(errors='replace').strip()))
    finally:
        shutil.rmtree(work, ignore_errors=True)


def check_measured(dataset):
    inputs = dataset['inputs']['files']
    runs = dataset['measurement']['runs']
    for row in dataset['results']:
        if row['check'] != 'measured':
            continue
        label = '%s / %s' % (row['option'], row['property'])
        rec = runs[row['run']]['files'][row['file']]
        problems = []
        for key, want in row['expect'].items():
            if isinstance(want, str) and want.startswith('input:'):
                want = inputs[want[len('input:'):]][key]
            if rec.get(key) != want:
                problems.append('%s is %r, expected %r' % (key, rec.get(key), want))
        if problems:
            report('FAIL', label, '; '.join(problems))
        else:
            report('RECORDED', label, 'account leg, not re-run; record consistent')

    saver = runs['storage saver, owner download (Shift+D)']['files'][1]
    mp = saver['width'] * saver['height'] / 1e6
    if round(mp, 1) == 16.0 and mp <= 16.0:
        report('RECORDED', 'Storage saver keeps at most 16 MP', '%.2f MP' % mp)
    else:
        report('FAIL', 'Storage saver keeps at most 16 MP', '%.2f MP' % mp)
    big = inputs['photo-48mp.heic']
    ratio = big['width'] / big['height']
    if abs(saver['width'] / saver['height'] - ratio) < 0.001:
        report('RECORDED', 'Storage saver keeps the aspect ratio')
    else:
        report('FAIL', 'Storage saver keeps the aspect ratio')


# ------------------------------------------------------------------------ csv

def check_csv(dataset):
    table = dataset['table']
    with open(CSV, encoding='utf-8', newline='') as fh:
        rows = list(csv.DictReader(fh))
    if rows == table['rows'] and list(rows[0].keys()) == table['columns']:
        report('OK', 'dataset.csv matches dataset.json', '%d rows' % len(rows))
    else:
        report('FAIL', 'dataset.csv matches dataset.json')


def main():
    recheck = '--recheck' in sys.argv
    with open(DATASET, encoding='utf-8') as fh:
        dataset = json.load(fh)

    if recheck:
        print('SKIPPED      test photos and recorded downloads (--recheck reads the pages only)')
    else:
        rebuild_inputs(dataset)
        check_measured(dataset)
        check_csv(dataset)

    root = repo_root()
    for row in dataset['results']:
        label = '%s / %s' % (row['option'], row['property'])
        kind = row['check']
        if kind == 'page':
            check_page(row, label)
        elif kind == 'record':
            check_record(row, label)
        elif kind == 'code' and not recheck:
            check_code(row, label, root)
        elif kind == 'product' and not recheck:
            report('RECORDED', label, row['source'])

    if failures:
        print('\n%d check(s) failed' % len(failures))
        return 1
    print('\nall checks hold')
    return 0


if __name__ == '__main__':
    sys.exit(main())
