"""Synthetic provenance demonstration; not production control or LiDAR registration.
Run: python reconstruction-demo.py reconstruction-events.csv
"""
import csv
import json
import sys
from datetime import datetime
from pathlib import Path


def reconstruct(path):
    records = []
    with path.open(newline='', encoding='utf-8') as source:
        for row_number, row in enumerate(csv.DictReader(source), start=2):
            row = {key: value.strip() for key, value in row.items()}
            captured = datetime.fromisoformat(row['captured_at'].replace('Z', '+00:00'))
            received = datetime.fromisoformat(row['received_at'].replace('Z', '+00:00'))
            if captured.tzinfo is None or received.tzinfo is None:
                raise ValueError('Observation times must include a timezone')
            row['source'] = f'{path.name}:row-{row_number}'
            records.append(row)
    records.sort(key=lambda row: row['captured_at'])
    spatial = [row for row in records if row['kind'] == 'spatial_capture']
    reasons = []
    if len(spatial) < 2:
        reasons.append('At least two spatial capture references are required')
    if len({row['captured_at'] for row in spatial}) > 1:
        reasons.append('Capture times differ; synchronized state is unsupported')
    if len({row['frame'] for row in spatial}) > 1:
        reasons.append('Coordinate frames differ and no qualified transform was supplied')
    if any(row['calibration_status'] != 'current' for row in spatial):
        reasons.append('Required calibration evidence is unavailable')
    if len({row['location'] for row in spatial}) > 1:
        reasons.append('Spatial references describe different locations')
    air = [float(row['value']) for row in records
           if row['kind'] == 'air_temperature' and row['unit'] == 'degC']
    return {'example_type': 'synthetic metadata only; no geometry registration',
            'fusion_allowed': not reasons, 'reasons': reasons, 'timeline': records,
            'air_temperature_observations_degC': air,
            'scope': 'Strict illustrative rule, not a universal fusion policy'}


if __name__ == '__main__':
    if len(sys.argv) != 2:
        raise SystemExit('Usage: python reconstruction-demo.py reconstruction-events.csv')
    print(json.dumps(reconstruct(Path(sys.argv[1])), indent=2))
