"""Synthetic readiness only; never executes the serial lifecycle loop."""
import copy
import hashlib
import json
from pathlib import Path
import subprocess
import tempfile

runner = Path(__file__).with_name('run-serial-lanes.zsh')
queries = json.loads((runner.parent.parent / 'monitoring/queries.json').read_text())
up = queries['identity'].replace('GENERATION', 'synthetic-generation')
expressions = {'up': up, 'scrape_count': f'count_over_time({up}[45s])',
    'scrape_min': f'min_over_time({up}[45s])', 'sample_age': f'time()-timestamp({up})',
    'collection_freshness': queries['collection_freshness']}
receipt = {'generation': 'synthetic-generation', 'evaluation_epoch': 100, 'queries': {}}
for key, expression in expressions.items():
    receipt['queries'][key] = {'query': expression, 'evaluation_epoch': 100,
        'response': {'status': 'success', 'data': {'result': [
            {'metric': {'registration_generation': 'synthetic-generation'},
             'value': [100, str(3 if key == 'scrape_count' else 5 if key == 'sample_age' else 1)]}]}}}
with tempfile.TemporaryDirectory() as temporary:
    path = Path(temporary) / 'receipt.json'
    def check(value):
        path.write_text(json.dumps(value))
        return subprocess.run(['zsh', str(runner), '--check-readiness', str(path),
            'synthetic-generation', '100'], capture_output=True, text=True)
    result = check(receipt)
    assert result.returncode == 0, result.stderr
    for key, value in [('scrape_count', '1'), ('scrape_min', '0'), ('sample_age', '31'),
                       ('sample_age', '-1'), ('collection_freshness', '0')]:
        bad = copy.deepcopy(receipt)
        bad['queries'][key]['response']['data']['result'][0]['value'][1] = value
        assert check(bad).returncode != 0, (key, value)
    bad = copy.deepcopy(receipt); bad['queries']['up']['response']['data']['result'] = []
    assert check(bad).returncode != 0
    bad = copy.deepcopy(receipt); bad['queries']['up']['response']['data']['result'][0]['metric']['registration_generation'] = 'other'
    assert check(bad).returncode != 0
    bad = copy.deepcopy(receipt); bad['queries']['up']['query'] = 'different'
    assert check(bad).returncode != 0
    def guard(mode, *args):
        return subprocess.run(['zsh', str(runner), mode, *map(str, args)], capture_output=True).returncode
    window = {'window_start_epoch': 9000, 'request_cutoff_epoch': 12900, 'wall_deadline_epoch': 14400,
        'arm': 'a', 'repetition': 2, 'audit': False, 'target_requests': 425, 'warmups': 27}
    window_path = Path(temporary) / 'window.json'
    window_path.write_text(json.dumps(window))
    assert guard('--check-window', window_path, 'a', 2, 10000) == 0
    assert guard('--check-window', window_path, 'a', 2, 12901) != 0
    assert guard('--check-window', window_path, 'b', 2, 10000) != 0
    for field, value in [('window_start_epoch', 11000), ('request_cutoff_epoch', 8000),
        ('request_cutoff_epoch', 12901), ('wall_deadline_epoch', 14401), ('wall_deadline_epoch', 14000),
        ('window_start_epoch', 'malformed'), ('request_cutoff_epoch', float('inf'))]:
        bad = dict(window, **{field: value}); window_path.write_text(json.dumps(bad))
        assert guard('--check-window', window_path, 'a', 2, 10000) != 0, (field, value)
    registry = Path(temporary) / 'registry.toml'; registry.write_text('frozen allocation')
    record = Path(temporary) / 'frozen-inputs.sha256'
    record.write_text(hashlib.sha256(registry.read_bytes()).hexdigest() + '  ' + str(registry) + '\n')
    assert guard('--check-registry', record, registry) == 0
    registry.write_text('changed same-image allocation')
    assert guard('--check-registry', record, registry) != 0
    range_path = Path(temporary) / 'range.json'
    ranged = {'status': 'success', 'data': {'resultType': 'matrix', 'result': [
        {'metric': {'__name__': 'up', 'registration_generation': 'g'}, 'values': [[100, '1']]}]}}
    range_path.write_text(json.dumps(ranged))
    assert guard('--check-range', range_path, 'identity', 'g') == 0
    assert guard('--check-range', range_path, 'identity', 'other') != 0
    ranged['data']['result'] = []; range_path.write_text(json.dumps(ranged))
    assert guard('--check-range', range_path, 'identity', 'g') != 0
print('PASS: synthetic readiness; finite bounded window/expiry guards; frozen registry drift; nonempty generation-bound ranges; no runner execution')
