"""Offline SQLite simulation with synthetic records, not Cloudflare execution.

Keep this file beside redact-ip.sql and input.synthetic.ndjson.
Run: python3 simulate.py
Transformed NDJSON goes to stdout; a local check summary goes to stderr.
"""

import json
from pathlib import Path
import sqlite3
import sys


def main():
    base = Path(__file__).resolve().parent
    source = [json.loads(line) for line in
              (base / 'input.synthetic.ndjson').read_text(encoding='utf-8').splitlines()
              if line.strip()]
    sql = (base / 'redact-ip.sql').read_text(encoding='utf-8')
    database = sqlite3.connect(':memory:')
    database.row_factory = sqlite3.Row
    try:
        database.execute('''CREATE TABLE http_requests (
            RayID TEXT, ClientIP TEXT, EdgeResponseStatus INTEGER,
            ClientRequestURI TEXT, ClientRequestUserAgent TEXT
        )''')
        database.executemany(
            'INSERT INTO http_requests VALUES (?, ?, ?, ?, ?)',
            [(row['RayID'], row['ClientIP'], row['EdgeResponseStatus'],
              row['ClientRequestURI'], row['ClientRequestUserAgent']) for row in source],
        )
        output = [dict(row) for row in database.execute(sql)]
    finally:
        database.close()

    expected = {
        '0000000000000001': 403,
        '0000000000000002': 502,
        '0000000000000004': 404,
    }
    assert {row['ray_id']: row['status'] for row in output} == expected
    assert len(output) == 3
    allowed = {'ray_id', 'status', 'client_ip_redacted', 'provider'}
    assert all(set(row) == allowed for row in output)
    assert all(row['client_ip_redacted'] == '[REDACTED]' for row in output)
    assert all(row['provider'] == 'cloudflare' for row in output)
    text = '\n'.join(json.dumps(row, ensure_ascii=False, separators=(',', ':'))
                     for row in output)
    for row in source:
        assert row['ClientIP'] not in text
        assert row['ClientRequestURI'] not in text
        assert row['ClientRequestUserAgent'] not in text
    print(text)
    print(json.dumps({
        'mode': 'local-sqlite-simulation-with-synthetic-data',
        'sqlite_version': sqlite3.sqlite_version,
        'input_records': len(source),
        'output_records': len(output),
        'filtered_records': len(source) - len(output),
        'field_allowlist_matches': True,
        'source_ip_and_uri_markers_absent': True,
        'cloudflare_preview_called': False,
        'destination_delivery_verified': False,
    }), file=sys.stderr)


if __name__ == '__main__':
    main()
