#!/usr/bin/env python3
"""Verify the synthetic Permit2 fixture with Python 3's standard library.

Usage: python3 permit2-nonce-verify.py [path/to/permit2-nonce-fixtures.json]
No network, wallet, contract execution, signature verification or chain read.
"""
import json
from pathlib import Path
import re
import sys

MAX_UINT256 = 2 ** 256 - 1


def parse_uint256(value):
    if not isinstance(value, str) or not value or len(value) > 78:
        raise ValueError('Expected a complete, bounded decimal or hexadecimal string.')
    if re.fullmatch(r'[0-9]+', value):
        result = int(value, 10)
    elif re.fullmatch(r'0[xX][0-9a-fA-F]{1,64}', value):
        result = int(value[2:], 16)
    else:
        raise ValueError('Whitespace, signs, fractions, separators and exponent notation are not accepted.')
    if result > MAX_UINT256:
        raise ValueError('Value exceeds uint256.')
    return result


def independent_answer(inputs):
    nonce = parse_uint256(inputs['nonce'])
    bitmap = parse_uint256(inputs['bitmap'])
    word, bit = divmod(nonce, 256)
    power = 2 ** bit
    occupied = (bitmap // power) % 2 == 1
    # This uses conditional addition, independently of production JS OR/AND.
    after = bitmap if occupied else bitmap + power
    return {
        'word_position': str(word),
        'bit_position': str(bit),
        'single_nonce_mask': str(power),
        'selected_bit': 'set' if occupied else 'clear',
        'expected_bitmap_after_or': str(after),
    }


def verify(path):
    fixture = json.loads(path.read_text(encoding='utf-8'))
    if fixture.get('evidence_type') != 'synthetic' or fixture.get('methodology_version') != '1.0.0':
        raise ValueError('Unsupported fixture evidence type or method version.')
    cases = fixture.get('cases')
    if not isinstance(cases, list) or not cases:
        raise ValueError('Fixture contains no test cases.')
    seen = set()
    for case in cases:
        identifier = case['id']
        if identifier in seen or case.get('evidence_type') != 'synthetic':
            raise ValueError('Duplicate case ID or missing synthetic label.')
        seen.add(identifier)
        actual = independent_answer(case['inputs'])
        if actual != case['expected']:
            raise ValueError('Independent expected-value mismatch in case ' + identifier)
    return {
        'status': 'passed',
        'cases_checked': len(cases),
        'methodology_version': fixture['methodology_version'],
        'scope': 'Independent exact integer recomputation of synthetic fixtures only.',
        'runtime_authorization_status': 'unknown',
        'chain_state_observed': False,
        'production_javascript_executed': False,
    }


if __name__ == '__main__':
    try:
        fixture_path = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).with_name('permit2-nonce-fixtures.json')
        print(json.dumps(verify(fixture_path), indent=2))
    except (OSError, ValueError, KeyError, TypeError) as error:
        print('Verification failed: ' + str(error), file=sys.stderr)
        sys.exit(1)
