#!/usr/bin/env python3
"""Original offline Bitcoin timelock boundary reference; no network or wallet calls.

Uses last-invalid thresholds and strict comparisons, independently of the
browser worksheet's first-eligible representation. It validates synthetic
fixtures only, not serialized Bitcoin transactions or scripts.
"""
import json
from pathlib import Path
import sys

FINAL = (1 << 32) - 1
DISABLE = 1 << 31
TYPE = 1 << 22
MASK = (1 << 16) - 1
THRESHOLD = 500_000_000


def reference(values):
    kind = values['kind']
    r, version, lock, seq, height, mtp, coin, base = (
        int(values[k]) for k in ('required', 'txVersion', 'txLockTime',
        'sequence', 'candidateHeight', 'candidateMtp', 'coinHeight', 'coinPrevMtp')
    )
    cltv = kind.startswith('cltv_')
    time_type = kind.endswith('_time')
    if coin < 1 or height <= coin:
        return {'decisionCode': 'context_mismatch'}
    if cltv:
        script_pass = (lock >= THRESHOLD) == time_type and lock >= r and seq != FINAL
    else:
        script_pass = version >= 2 and not (seq & DISABLE) and bool(seq & TYPE) == time_type and (seq & MASK) >= r
    if not script_pass:
        return {'decisionCode': 'script_requirement_failed'}

    last_heights, last_times = [], []
    result = {'relativeLastInvalidHeight': None, 'relativeLastInvalidMtp': None,
              'relativeDelaySeconds': None}
    if lock:
        (last_heights if lock < THRESHOLD else last_times).append(lock)
    if version >= 2 and not (seq & DISABLE):
        count = seq & MASK
        if seq & TYPE:
            if mtp < base:
                return {'decisionCode': 'context_mismatch'}
            last_invalid = base + (count << 9) - 1
            last_times.append(last_invalid)
            result['relativeLastInvalidMtp'] = str(last_invalid)
            result['relativeDelaySeconds'] = str(count << 9)
        else:
            last_invalid = coin + count - 1
            last_heights.append(last_invalid)
            result['relativeLastInvalidHeight'] = str(last_invalid)
    height_pass = not last_heights or height > max(last_heights)
    time_pass = not last_times or mtp > max(last_times)
    first_height = max(last_heights) + 1 if last_heights else None
    first_mtp = max(last_times) + 1 if last_times else None
    result.update({
        'decisionCode': 'conditions_met' if height_pass and time_pass else 'timelock_unmet',
        'firstCandidateHeight': str(first_height) if first_height is not None else None,
        'firstPriorBlockMtp': str(first_mtp) if first_mtp is not None else None,
        'remainingBlocks': str(max(0, first_height - height)) if first_height is not None else None,
        'remainingMtpSeconds': str(max(0, first_mtp - mtp)) if first_mtp is not None else None,
    })
    return result


def main():
    source = Path(sys.argv[1]) if len(sys.argv) == 2 else Path(__file__).with_name('timelock_boundary_cases.json')
    fixture = json.loads(source.read_text(encoding='utf-8'))
    checks = []
    for case in fixture['cases']:
        actual = reference(case['inputs'])
        for key, expected in case['expected'].items():
            if actual.get(key) != expected:
                raise AssertionError(f"{case['id']}: {key}: expected {expected!r}, got {actual.get(key)!r}")
        checks.append({'id': case['id'], 'passed': True,
                       'observed': {k: actual[k] for k in case['expected']}})
    print(json.dumps({'evidence_date': fixture['evidence_date'],
                      'fixture_type': 'synthetic; not live chain data',
                      'method': 'Original Python integer reference using last-invalid thresholds and strict comparisons',
                      'count': len(checks), 'passed': len(checks), 'failed': 0,
                      'cases': checks}, indent=2, sort_keys=True))


if __name__ == '__main__':
    main()
