#!/usr/bin/env python3
"""Receive a clinic's collected audit JSON over authenticated SSH, never raw binlogs."""
import argparse
import datetime as dt
import fcntl
import json
import os
import sys
import tempfile
from pathlib import Path
from zoneinfo import ZoneInfo

ZONE = ZoneInfo('Asia/Yangon')
MAX_BYTES = 30 * 1024 * 1024


def stamp(value):
    parsed = dt.datetime.fromisoformat(value)
    if parsed.tzinfo is None:
        raise ValueError('Timestamp needs a timezone')
    return parsed.astimezone(ZONE)


def receive(root, clinic, payload, now=None):
    now = now or dt.datetime.now(ZONE)
    registry = json.loads((root / 'sources.json').read_text())
    source = registry.get(clinic)
    if not source:
        raise ValueError('Clinic is not provisioned')
    snapshot = payload.get('snapshot', {})
    if snapshot.get('database') != source['database'] or snapshot.get('source_id') != source['source_id']:
        raise ValueError('Clinic snapshot identity mismatch')
    if snapshot.get('version') != 1 or snapshot.get('collector_format') != 2 or not isinstance(snapshot.get('events'), list):
        raise ValueError('Unsupported snapshot format')
    until, start = stamp(snapshot['until']), stamp(snapshot['from'])
    coverage = stamp(snapshot['coverage_start'])
    if start > until or until > now + dt.timedelta(minutes=5) or until < now - dt.timedelta(minutes=15):
        raise ValueError('Snapshot is stale or has an invalid window')
    if until - start > dt.timedelta(days=101):
        raise ValueError('Snapshot window exceeds 100-day collection allowance')
    if not isinstance(snapshot.get('table_operations', []), list) or not isinstance(snapshot.get('coverage_complete'), bool):
        raise ValueError('Invalid coverage metadata')
    seen = set()
    for event in snapshot['events']:
        if event.get('action') not in ('update', 'delete') or not isinstance(event.get('before'), dict) or not isinstance(event.get('after'), dict):
            raise ValueError('Invalid row event')
        key = event.get('key')
        if not isinstance(key, str) or not key or key in seen:
            raise ValueError('Invalid or duplicate event identity')
        seen.add(key)
        if not start <= stamp(event['committed_at']) < until:
            raise ValueError('Event is outside snapshot window')
    status = payload.get('collector_status', {})
    if not isinstance(status, dict) or status.get('ok') is not True:
        raise ValueError('Collector did not report success')
    target = root / (clinic + '.json')
    with (root / ('.' + clinic + '.lock')).open('a') as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)
        if target.exists():
            previous = json.loads(target.read_text())
            if stamp(previous['snapshot']['until']) > until:
                raise ValueError('An older snapshot cannot replace newer history')
        envelope = {'version': 1, 'clinic': clinic, 'received_at': now.isoformat(), 'snapshot': snapshot, 'collector_status': status}
        handle, name = tempfile.mkstemp(prefix='.receiving-', dir=root)
        try:
            with os.fdopen(handle, 'w') as output:
                json.dump(envelope, output, ensure_ascii=False, separators=(',', ':'))
                output.write('\n'); output.flush(); os.fsync(output.fileno())
            os.chmod(name, 0o640)
            # The private receiver directory inherits the web-worker group via setgid.
            os.replace(name, target)
        finally:
            if os.path.exists(name):
                os.unlink(name)
    return {'ok': True, 'clinic': clinic, 'received_at': now.isoformat(), 'collected_at': until.isoformat(), 'events': len(snapshot['events'])}


def main():
    os.umask(0o027)
    parser = argparse.ArgumentParser()
    parser.add_argument('--root', type=Path, default=Path(__file__).resolve().parents[2] / 'storage/app/ncd-clinic-history')
    parser.add_argument('--clinic', required=True, choices=['MAM_A', 'MAM_B', 'MAM_C1', 'MAM_SPT', 'MAM_SDG', 'MAM_TL', 'MAM_TBZY', 'MAM_PDT'])
    args = parser.parse_args()
    raw = sys.stdin.buffer.read(MAX_BYTES + 1)
    if len(raw) > MAX_BYTES:
        raise ValueError('Payload exceeds maximum size')
    result = receive(args.root, args.clinic, json.loads(raw))
    print(json.dumps(result))


if __name__ == '__main__':
    try:
        main()
    except Exception as error:
        # Do not echo patient data or connection credentials into transfer logs.
        print(json.dumps({'ok': False, 'message': str(error) if isinstance(error, ValueError) else 'Audit snapshot could not be received'}), file=sys.stderr)
        sys.exit(1)
