#!/usr/bin/env python3
"""Verify three reported tables in one pinned public PDF; no model evaluation."""
import argparse
import hashlib
import json
from pathlib import Path
import re
import subprocess
import sys

PDF_SHA256 = '55f6ed1c0735ec1b5b14d99c91794fb759ac4647edc64381123b68be89fd3225'
MODELS = ['Claude Mythos Preview', 'Claude Sonnet 4.6', 'Claude Opus 4.6']
EXPECTED = {
    'coding': [[0, 0, 0, 0], [.03, 2.5, 0, 0], [0, 0, 0, 0], [.1, 7.5, .04, 5], [0, 0, 0, 0], [0, 0, 0, 0]],
    'computer_use': [[.43, 21.43, .32, 21.43], [.39, 14.29, .36, 14.29], [12, 42.9, 8, 50], [14.4, 64.3, 8.6, 50], [17.8, 78.6, 9.7, 57.1], [20, 85.7, 10, 64.3]],
    'browser_transfer': [[.68, 0], [55.41, 4.05], [80.41, 7.43]],
}
MARKERS = {'coding': '[Table 8.3.2.2.1.A]', 'computer_use': '[Table 8.3.2.2.2.A]', 'browser_transfer': '[Table 8.3.2.2.3.A]'}


def inspect(pdf):
    digest = hashlib.sha256(pdf.read_bytes()).hexdigest()
    if digest != PDF_SHA256:
        raise ValueError('PDF differs from the reviewed revision; inspect it before updating the expected hash or tables')
    text = subprocess.run(['pdftotext', '-layout', str(pdf), '-'], check=True, capture_output=True, text=True).stdout
    pages = text.split('\f')
    result = {'pdf_sha256': digest, 'kind': 'published_table_verification_only', 'tables': {}}
    for kind, marker in MARKERS.items():
        found = [(i, p.split(marker)[0]) for i, p in enumerate(pages, 1) if marker in p]
        if len(found) != 1:
            raise ValueError(f'{kind}: expected exactly one table caption')
        page, table = found[0]
        if kind == 'browser_transfer':
            lines = [line for line in table.splitlines() if line.lstrip().startswith('Claude') and '%' in line]
        else:
            lines = [line for line in table.splitlines() if re.search(r'(Extended|Standard) thinking', line)]
            modes = [re.search(r'(Extended|Standard) thinking', line).group(1) for line in lines]
            if modes != ['Extended', 'Standard'] * 3:
                raise ValueError(f'{kind}: unexpected thinking-mode order')
        values = [[float(v) for v in re.findall(r'(\d+(?:\.\d+)?)%', line)] for line in lines]
        if values != EXPECTED[kind]:
            raise ValueError(f'{kind}: extracted values differ from the reviewed table: {values}')
        rows = []
        for index, value in enumerate(values):
            row = {'model': MODELS[index if kind == 'browser_transfer' else index // 2], 'percentages': value}
            if kind != 'browser_transfer':
                row['thinking'] = 'extended' if index % 2 == 0 else 'standard'
            rows.append(row)
        result['tables'][kind] = {'physical_pdf_page': page, 'caption': marker, 'rows': rows,
            'columns': ['without_safeguards', 'with_safeguards'] if kind == 'browser_transfer' else ['without_1_attempt', 'without_200_attempts', 'with_1_attempt', 'with_200_attempts']}
    return result


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('pdf', type=Path)
    args = parser.parse_args()
    try:
        print(json.dumps(inspect(args.pdf), indent=2))
    except (OSError, ValueError, subprocess.CalledProcessError) as exc:
        print(f'CHECK FAILED: {exc}', file=sys.stderr)
        return 1
    return 0


if __name__ == '__main__':
    raise SystemExit(main())
