#!/usr/bin/env python3
"""Compare or atomically synchronize the complete Mongo state catalog.

Dry-run is the default. Applying requires migration 0055 and an explicit target host.
Optional expected counts are available for audits; valid additions are accepted by default.
"""
import argparse
import json
import re
import sys
import uuid
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from urllib.parse import urlsplit
from state_catalog import (
    DETAIL_FIELDS, BLOCKED_KEY, CODE, SupabaseReadWrite, canonical_ids, env_file,
    json_safe, prepare_rows, setting, compare_snapshot, claim_sync, publish_snapshot,
)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--mongo-env')
    parser.add_argument('--workspace-env', default='.env')
    parser.add_argument('--expect-docs', type=int)
    parser.add_argument('--expect-codes', type=int)
    parser.add_argument('--apply', action='store_true')
    parser.add_argument('--confirm-target')
    args = parser.parse_args()
    source, target = env_file(args.mongo_env), env_file(args.workspace_env)
    mongo_uri = setting('MONGO_URI', source)
    db_name = setting('DB_NAME', source) or setting('MONGO_DB_NAME', source) or 'HeavyHaulDB'
    url, key = setting('NEXT_PUBLIC_SUPABASE_URL', target), setting('SUPABASE_SERVICE_ROLE_KEY', target)
    if not mongo_uri or not url or not key:
        raise ValueError('Mongo and Supabase configuration is required')
    parsed = urlsplit(url)
    if not parsed.hostname or (parsed.scheme != 'https' and parsed.hostname not in ('localhost', '127.0.0.1')):
        raise ValueError('Supabase target must use HTTPS')
    if args.apply and args.confirm_target != parsed.hostname:
        raise ValueError('Apply requires confirm-target matching the configured host')
    from pymongo import MongoClient
    import certifi
    with MongoClient(mongo_uri, tlsCAFile=certifi.where(), serverSelectionTimeoutMS=10000,
                     appname='workspace-state-catalog-sync') as mongo:
        documents = list(mongo[db_name]['all_states'].find({}))
    rows, duplicates = prepare_rows(documents)
    codes = len({row['state_code'] for row in rows})
    if ((args.expect_docs is not None and len(rows) != args.expect_docs) or
        (args.expect_codes is not None and codes != args.expect_codes)):
        raise ValueError('State count differs from the requested audit count')
    client = SupabaseReadWrite(url, key)
    existing = client.existing()
    changed, missing = compare_snapshot(rows, existing)
    print(json.dumps({'mode': 'apply' if args.apply else 'dry_run', 'mongo_documents': len(rows),
        'unique_codes': codes, 'duplicate_codes': duplicates, 'changed': len(changed),
        'removed': len(missing), 'unchanged': len(rows)-len(changed)}))
    if args.apply:
        holder = 'manual-' + str(uuid.uuid4())
        if not claim_sync(client, holder):
            raise RuntimeError('Another state sync owns the publication lease')
        try:
            print(json.dumps(publish_snapshot(client, rows, holder)))
        finally:
            client.rpc('release_state_catalog_sync', {'p_holder': holder})
    return 0


if __name__ == '__main__':
    try:
        sys.exit(main())
    except Exception as error:
        message = str(error)
        safe = message if re.fullmatch(r'[A-Za-z0-9_. :,;()/-]{1,180}', message) else type(error).__name__
        print('State sync stopped: ' + safe, file=sys.stderr)
        sys.exit(1)
