#!/usr/bin/env python3
"""Recompute DN's declared synthetic examples; Python 3 standard library only.

Keep this file beside the downloaded pNN.json and pNN.csv files, then run:
    python3 verify.py p31.json
Without filenames it checks every pNN.json beside this script. This checks
arithmetic and CSV/JSON agreement, not source truth, eligibility or performance.
"""
import argparse
import ast
import csv
import datetime as dt
import json
import math
import operator
from pathlib import Path

OPS = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul,
       ast.Div: operator.truediv, ast.FloorDiv: operator.floordiv,
       ast.Pow: operator.pow, ast.Mod: operator.mod}
FUNCTIONS = {'min': min, 'max': max, 'int': int, 'round': round,
             'days_between': lambda a, b: (dt.date.fromisoformat(b) - dt.date.fromisoformat(a)).days}

def calculate(expression):
    def visit(node):
        if isinstance(node, ast.Constant) and type(node.value) in (int, float, str):
            return node.value
        if isinstance(node, ast.BinOp) and type(node.op) in OPS:
            return OPS[type(node.op)](visit(node.left), visit(node.right))
        if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.UAdd, ast.USub)):
            return visit(node.operand) * (-1 if isinstance(node.op, ast.USub) else 1)
        if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id in FUNCTIONS and not node.keywords:
            return FUNCTIONS[node.func.id](*[visit(a) for a in node.args])
        raise ValueError('Unsupported expression syntax')
    return visit(ast.parse(expression, mode='eval').body)

def text_cell(value):
    return '' if value is None else str(value)

def verify(path):
    data = json.loads(path.read_text(encoding='utf-8'))
    failures = []
    if data.get('example', {}).get('synthetic') is not True:
        failures.append('Missing explicit synthetic label')
    calculations = data.get('calculations', [])
    if not calculations:
        failures.append('No calculations supplied')
    for item in calculations:
        try:
            actual = calculate(item['expression'])
            if not math.isfinite(actual) or not math.isclose(actual, item['expected'], rel_tol=1e-8, abs_tol=1e-8):
                failures.append('Arithmetic mismatch: ' + item['label'])
        except (ValueError, TypeError, KeyError, ArithmeticError, SyntaxError) as exc:
            failures.append('Invalid calculation: ' + str(exc))
    csv_path = path.with_suffix('.csv')
    if not csv_path.exists():
        failures.append('Keep the matching CSV beside the JSON file: ' + csv_path.name)
    else:
        with csv_path.open(newline='', encoding='utf-8') as handle:
            rows = list(csv.reader(handle))
        columns = data.get('input_schema', {}).get('columns')
        example_rows = data.get('example', {}).get('rows')
        if not isinstance(columns, list) or not columns or any(not isinstance(c, str) or not c for c in columns) or len(set(columns)) != len(columns):
            failures.append('JSON columns must be distinct nonempty strings')
            columns = []
        if not isinstance(example_rows, list) or not example_rows:
            failures.append('JSON example rows must be a nonempty list')
            example_rows = []
        expected = [columns]
        for row in example_rows:
            if isinstance(row, dict):
                if set(row) != set(columns):
                    failures.append('JSON object row must match all declared columns exactly')
                    continue
                values = [row[column] for column in columns]
            elif isinstance(row, list):
                values = row
            else:
                failures.append('JSON example row must be a list or object')
                continue
            if len(values) != len(columns):
                failures.append('JSON example row width differs from declared columns')
            if any(value is not None and type(value) not in (str, int, float, bool) for value in values):
                failures.append('JSON example cells must be scalar strings, numbers, booleans or null')
            if any(type(value) in (int, float) and not math.isfinite(value) for value in values):
                failures.append('JSON example contains a non-finite number')
            expected.append(values)
        if rows != [[text_cell(v) for v in row] for row in expected]:
            failures.append('CSV differs from the versioned JSON example')
        if any(len(row) != len(columns) for row in rows):
            failures.append('CSV column count mismatch')
    return {'file': path.name, 'record_id': data.get('record_id'),
            'calculations': len(calculations), 'pass': not failures, 'failures': failures}

def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('files', nargs='*', type=Path)
    parser.add_argument('--expect-count', type=int)
    args = parser.parse_args()
    paths = args.files or sorted(Path(__file__).resolve().parent.glob('p[0-9][0-9].json'))
    results = [verify(path) for path in paths]
    passed = bool(results) and all(r['pass'] for r in results)
    if args.expect_count is not None and len(paths) != args.expect_count:
        passed = False
    print(json.dumps({'scope': 'Declared synthetic arithmetic and CSV/JSON consistency only',
                      'records': len(results), 'calculations': sum(r['calculations'] for r in results),
                      'pass': passed, 'results': results}, indent=2))
    return 0 if passed else 1

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