#!/usr/bin/env python3
"""Reproduce the index and recovery articles in a disposable local PostgreSQL cluster.

No connection string is accepted: this script never connects to an existing server.
Requires the PostgreSQL command-line tools, Python 3 and no third-party modules.
"""
import argparse
from datetime import datetime, timezone
import json
import os
from pathlib import Path
import shlex
import statistics
import subprocess
import tempfile
import time


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--postgres-bin', required=True, type=Path)
    parser.add_argument('--output', type=Path, default=Path('postgresql-lab-results.json'))
    args = parser.parse_args()
    bindir = args.postgres_bin.resolve()
    for name in ['initdb', 'pg_ctl', 'psql', 'createdb', 'pg_dump', 'pg_restore']:
        if not (bindir / name).is_file():
            parser.error(f'Missing PostgreSQL executable: {name}')
    with tempfile.TemporaryDirectory(prefix='lb-lab-', dir='/tmp') as tmp:
        base = Path(tmp)
        data = base / 'data'
        sockets = base / 'socket'
        sockets.mkdir()
        env = {**os.environ, 'PGHOST': str(sockets), 'PGPORT': '55492', 'PGUSER': 'lab', 'PGDATABASE': 'postgres'}
        # Ignore any inherited connection/password settings; only this socket is used.
        for key in ['PGSERVICE', 'PGSERVICEFILE', 'PGPASSWORD', 'PGPASSFILE', 'PGHOSTADDR', 'PGOPTIONS']:
            env.pop(key, None)
        env['PGPASSFILE'] = str(base / 'no-password-file')

        def command(name, *params):
            return subprocess.run([str(bindir / name), *map(str, params)], env=env,
                                  text=True, capture_output=True, check=True).stdout

        def sql(query, database='source'):
            return command('psql', '-X', '-A', '-t', '-v', 'ON_ERROR_STOP=1', '-d', database, '-c', query).strip()

        command('initdb', '-D', data, '-U', 'lab', '--auth-local=trust', '--auth-host=reject', '--no-locale', '--encoding=UTF8')
        options = f"-k {shlex.quote(str(sockets))} -h '' -p 55492 -c max_connections=10"
        command('pg_ctl', '-D', data, '-l', base / 'server.log', '-o', options, '-w', 'start')
        try:
            command('createdb', 'source')
            sql("CREATE TABLE orders (id integer PRIMARY KEY, customer_id integer NOT NULL, payload text NOT NULL)")
            sql("INSERT INTO orders SELECT n, n % 10000, repeat(md5(n::text), 3) FROM generate_series(1, 200000) AS n")
            sql('ANALYZE orders')
            query = 'SELECT id, payload FROM orders WHERE customer_id = 4242'

            def measure():
                sql(query)  # warm up; both cases use the same warm-cache policy
                plans = [json.loads(sql('EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ' + query))[0] for _ in range(5)]
                return {'runs': 5, 'execution_ms': [p['Execution Time'] for p in plans],
                        'median_execution_ms': statistics.median(p['Execution Time'] for p in plans),
                        'plan': plans[-1]['Plan']}

            before = measure()
            rows_before = sql(query + ' ORDER BY id')
            sql('CREATE INDEX orders_customer_id_idx ON orders(customer_id)')
            sql('ANALYZE orders')
            after = measure()
            assert sql(query + ' ORDER BY id') == rows_before, 'Index changed query results'
            signature = "SELECT count(*), md5(string_agg(id::text || ':' || customer_id::text || ':' || payload, ',' ORDER BY id)) FROM orders"
            source_signature = sql(signature)
            start = time.monotonic()
            command('pg_dump', '-Fc', '--no-owner', '--no-privileges', '-f', base / 'backup.dump', 'source')
            dump_seconds = time.monotonic() - start
            command('createdb', 'restored')
            start = time.monotonic()
            command('pg_restore', '--exit-on-error', '--no-owner', '--no-privileges', '-d', 'restored', base / 'backup.dump')
            restore_seconds = time.monotonic() - start
            restored_signature = sql(signature, 'restored')
            assert source_signature == restored_signature, 'Restored rows differ from the source'
            index_restored = sql("SELECT count(*) FROM pg_indexes WHERE tablename='orders' AND indexname='orders_customer_id_idx'", 'restored') == '1'
            assert index_restored, 'Index missing after restore'
            result = {'date': datetime.now(timezone.utc).date().isoformat(), 'environment': 'Disposable local PostgreSQL; Unix socket; not a hosted LordBase benchmark',
                      'server_version': sql('SHOW server_version'), 'rows': 200000, 'matched_rows': 20,
                      'query': query, 'index': {'before': before, 'after': after, 'same_results': True},
                      'recovery': {'dump_seconds': round(dump_seconds, 4), 'restore_seconds': round(restore_seconds, 4),
                                   'archive_bytes': (base / 'backup.dump').stat().st_size, 'source_signature': source_signature,
                                   'restored_signature': restored_signature, 'index_restored': index_restored,
                                   'same_rows': True, 'source_writes_during_backup': False}}
            args.output.parent.mkdir(parents=True, exist_ok=True)
            args.output.write_text(json.dumps(result, indent=2) + '\n')
            print(json.dumps({'version': result['server_version'], 'rows': result['rows'],
                              'before_ms': before['median_execution_ms'], 'after_ms': after['median_execution_ms'],
                              'recovery': result['recovery']}, indent=2))
        finally:
            command('pg_ctl', '-D', data, '-m', 'fast', '-w', 'stop')


if __name__ == '__main__':
    main()
