#!/usr/bin/env python3
"""Persistent Mongo→Supabase state mirror. Requires migration 0055.

Uses change streams where available, plus hourly full reconciliation.
--mode poll provides a one-minute alternative where change streams are unavailable.
"""
import argparse
import json
import signal
import threading
import time
import uuid
from urllib.parse import urlsplit
from state_catalog import env_file, setting, SupabaseReadWrite, prepare_rows, compare_snapshot, claim_sync, publish_snapshot


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--mongo-env')
    parser.add_argument('--workspace-env')
    parser.add_argument('--apply', action='store_true')
    parser.add_argument('--confirm-target')
    parser.add_argument('--mode', choices=['auto', 'watch', 'poll'], default='auto')
    parser.add_argument('--poll-seconds', type=int, default=60)
    parser.add_argument('--reconcile-seconds', type=int, default=3600)
    parser.add_argument('--once', action='store_true')
    args = parser.parse_args()
    if not args.apply:
        raise ValueError('Run sync-gpt-states.py for a read-only dry-run')
    if args.poll_seconds < 10 or args.reconcile_seconds < 60:
        raise ValueError('Invalid synchronization intervals')
    source, target = env_file(args.mongo_env), env_file(args.workspace_env)
    uri = setting('MONGO_URI', source)
    db_name = setting('DB_NAME', source) or setting('MONGO_DB_NAME', source) or 'HeavyHaulDB'
    url = setting('NEXT_PUBLIC_SUPABASE_URL', target)
    key = setting('SUPABASE_SERVICE_ROLE_KEY', target)
    parsed = urlsplit(url)
    if not uri or not url or not key or parsed.scheme != 'https' or args.confirm_target != parsed.hostname:
        raise ValueError('Configure Mongo and confirm the HTTPS Supabase target')
    from pymongo import MongoClient
    from pymongo.errors import OperationFailure
    from bson import json_util
    import certifi
    mongo = MongoClient(uri, tlsCAFile=certifi.where(), serverSelectionTimeoutMS=10000,
        connectTimeoutMS=10000, socketTimeoutMS=20000, appname='workspace-state-catalog-worker')
    collection = mongo[db_name]['all_states']
    client = SupabaseReadWrite(url, key)
    heartbeat_client = SupabaseReadWrite(url, key)
    holder, stop, lost = 'worker-'+str(uuid.uuid4()), threading.Event(), threading.Event()
    for sig in (signal.SIGINT, signal.SIGTERM):
        signal.signal(sig, lambda *_: stop.set())
    if not claim_sync(client, holder):
        raise RuntimeError('Another state mirror holds the lease')

    def heartbeat():
        while not stop.wait(30):
            try:
                if not claim_sync(heartbeat_client, holder):
                    lost.set(); return
            except Exception:
                lost.set(); return

    threading.Thread(target=heartbeat, daemon=True).start()
    stream = None
    token = None
    try:
        # A fresh client for status reads avoids endpoint mutation in the heartbeat client.
        status_client = SupabaseReadWrite(url, key)
        status_client.base = status_client.root + '/state_catalog_sync_status'
        status_rows = status_client.request('GET', '?select=resume_token&singleton=eq.true')
        saved = status_rows[0].get('resume_token') if status_rows else None
        token = json_util.loads(json.dumps(saved)) if saved else None
        mode = args.mode
        if mode != 'poll':
            try:
                stream = collection.watch(full_document='updateLookup', resume_after=token,
                    max_await_time_ms=1000)
            except OperationFailure as error:
                if error.code in (286, 260, 136):
                    token = None
                    stream = collection.watch(full_document='updateLookup', max_await_time_ms=1000)
                elif mode == 'auto' and error.code in (13, 303, 40573):
                    mode = 'poll'; token = None
                    print(json.dumps({'event': 'change_stream_unavailable', 'mode': 'poll'}), flush=True)
                else:
                    raise

        def reconcile():
            if lost.is_set():
                raise RuntimeError('Mirror lease lost')
            documents = list(collection.find({}))
            rows, _ = prepare_rows(documents)
            compare_snapshot(rows, client.existing())
            encoded = json.loads(json_util.dumps(token)) if token else None
            result = publish_snapshot(client, rows, holder, encoded)
            print(json.dumps({'event': 'state_catalog_synced', **result}), flush=True)

        reconcile()  # Stream is established first, so startup writes remain observable.
        if args.once:
            return 0
        next_full = time.monotonic()+(args.poll_seconds if mode == 'poll' else args.reconcile_seconds)
        failures = 0
        while not stop.is_set() and not lost.is_set():
            try:
                event = stream.try_next() if stream else None
                if event and event.get('operationType') in ('invalidate', 'drop', 'rename', 'dropDatabase'):
                    raise RuntimeError('State collection invalidated; serving catalog preserved')
                if stream and stream.resume_token:
                    token = stream.resume_token
                if event or time.monotonic() >= next_full:
                    reconcile()
                    next_full = time.monotonic()+(args.poll_seconds if mode == 'poll' else args.reconcile_seconds)
                failures = 0
                if not stream:
                    stop.wait(min(5, args.poll_seconds))
            except OperationFailure:
                # Supervisor restart loads the last successfully committed checkpoint.
                raise
            except (RuntimeError, ValueError, OSError) as error:
                if 'invalidated' in str(error) or lost.is_set():
                    raise
                failures += 1
                print(json.dumps({'event': 'state_sync_retry', 'error_type': type(error).__name__}), flush=True)
                try:
                    client.rpc('report_state_catalog_sync_error', {'p_holder': holder, 'p_code': type(error).__name__})
                except Exception:
                    pass
                # Keep the stream token for the failed batch and retry before consuming more events.
                while not stop.wait(min(60, 2**min(failures, 6))) and not lost.is_set():
                    try:
                        reconcile(); failures = 0; break
                    except Exception:
                        failures += 1
        return 1 if lost.is_set() else 0
    except Exception as error:
        code = 'source_collection_invalidated' if 'invalidated' in str(error) else type(error).__name__
        try:
            client.rpc('report_state_catalog_sync_error', {'p_holder': holder, 'p_code': code})
        except Exception:
            pass
        raise
    finally:
        stop.set()
        if stream:
            stream.close()
        mongo.close()
        try:
            client.rpc('release_state_catalog_sync', {'p_holder': holder})
        except Exception:
            pass


if __name__ == '__main__':
    try:
        raise SystemExit(main())
    except Exception as error:
        print(json.dumps({'event': 'state_mirror_stopped', 'error_type': type(error).__name__}), flush=True)
        raise SystemExit(1)
