"""Offline intervals between counter observations; no transaction attribution."""
import argparse
import json
from datetime import datetime, timezone
from pathlib import Path


def counter_intervals(rows):
    if not isinstance(rows, list):
        raise ValueError('Expected a list of counter observations')
    result, previous = [], None
    for row in rows:
        if not isinstance(row, dict) or not isinstance(row.get('observed_at'), str):
            raise ValueError('Expected an observed_at timestamp')
        count = row.get('count')
        if type(count) is not int or count < 0:
            raise ValueError('Expected a nonnegative integer count')
        stamp = datetime.fromisoformat(row['observed_at'].replace('Z', '+00:00'))
        if stamp.utcoffset() is None:
            raise ValueError('Timezone required')
        stamp = stamp.astimezone(timezone.utc)
        if previous is not None:
            old_stamp, old_count = previous
            if stamp <= old_stamp:
                raise ValueError('Observations must be strictly chronological')
            delta = count - old_count
            result.append(dict(
                observed_from=old_stamp.isoformat(), observed_to=stamp.isoformat(),
                observation_gap_seconds=(stamp - old_stamp).total_seconds(),
                net_counter_change=delta,
                status='counter_decreased' if delta < 0 else 'net_change_observed',
                payment_time_verified=False,
            ))
        previous = stamp, count
    return result


def self_test():
    first = dict(observed_at='2026-10-25T12:00:00Z', count=10)
    second = dict(observed_at='2026-10-25T12:10:00Z', count=13)
    item = counter_intervals([first, second])[0]
    assert item['net_counter_change'] == 3
    assert item['observation_gap_seconds'] == 600
    assert item['payment_time_verified'] is False
    assert counter_intervals([first, dict(second, count=10)])[0]['net_counter_change'] == 0
    assert counter_intervals([first, dict(second, count=2)])[0]['status'] == 'counter_decreased'
    assert counter_intervals([]) == []
    for rows in ([second, first], [first, first], [dict(first, count=True)],
                 [dict(first, observed_at='2026-10-25T12:00:00')]):
        try:
            counter_intervals(rows)
        except ValueError:
            pass
        else:
            raise AssertionError('Invalid observations accepted')
    print('10 synthetic checks passed; no marketplace or blockchain requests')


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--self-test', action='store_true')
    parser.add_argument('--file', type=Path)
    args = parser.parse_args()
    if args.self_test:
        self_test()
    elif args.file:
        print(json.dumps(counter_intervals(json.loads(args.file.read_text())), indent=2))
    else:
        parser.error('Choose --self-test or --file OBSERVATIONS_JSON')
