"""Reproduce only in an owned, disposable PostgreSQL17 container, without ports.
Usage: python3 experiment.py --container YOUR_DISPOSABLE_CONTAINER
Requires Docker CLI and psql inside that container. Standard library only.
Drops/recreates ONLY the named exclusion_lab schema. Never use a shared database.
No application, ORM, performance benchmark, production traffic or AI/API calls.
"""
import argparse
from concurrent.futures import ThreadPoolExecutor
import json
import subprocess
import time


class Session:
    def __init__(self, container):
        self.process = subprocess.Popen(
            ['docker', 'exec', '-i', container, 'sh', '-c', 'exec psql -XAtq -U postgres 2>&1'],
            stdin=subprocess.PIPE, stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT, text=True,
        )
        self.query("SET statement_timeout='10s'; SET search_path=exclusion_lab,public;")

    def query(self, sql):
        self.process.stdin.write(sql+'\n\\echo __STATE__ :SQLSTATE\n\\echo __END__\n')
        self.process.stdin.flush()
        rows, state = [], None
        while True:
            line = self.process.stdout.readline()
            if not line:
                raise RuntimeError('Lab session ended: '+repr(rows))
            line = line.strip()
            if line == '__END__':
                assert state is not None, rows
                return state, rows
            if line.startswith('__STATE__ '):
                state = line.split()[-1]
            elif line:
                rows.append(line)

    def ok(self, sql):
        state, rows = self.query(sql)
        assert state == '00000', (state, rows)
        return rows

    def close(self):
        if self.process.poll() is None:
            self.process.stdin.write('\\q\n')
            self.process.stdin.flush()
            self.process.stdin.close()
            self.process.wait(timeout=15)
        assert self.process.returncode == 0


def run(container):
    a, b, observer = [Session(container) for _ in range(3)]
    cases, probes = [], []
    try:
        version = a.ok('SHOW server_version;')[0]
        assert version.startswith('17.11'), version
        a.ok('DROP SCHEMA IF EXISTS exclusion_lab CASCADE; CREATE SCHEMA exclusion_lab;')
        a.ok('CREATE EXTENSION IF NOT EXISTS btree_gist;')
        ddl = """CREATE TABLE reservations (
 id bigint PRIMARY KEY,
 tenant_id bigint NOT NULL,
 resource_id bigint NOT NULL,
 slot tstzrange NOT NULL,
 status text NOT NULL CHECK (status IN ('active','cancelled')),
 CONSTRAINT valid_slot CHECK (
   NOT isempty(slot) AND NOT lower_inf(slot) AND NOT upper_inf(slot)
   AND isfinite(lower(slot)) AND isfinite(upper(slot))
   AND lower_inc(slot) AND NOT upper_inc(slot)
 ),
 CONSTRAINT no_active_overlap EXCLUDE USING gist (
   tenant_id WITH =, resource_id WITH =, slot WITH &&
 ) WHERE (status = 'active') DEFERRABLE INITIALLY IMMEDIATE
);"""
        a.ok(ddl)
        def insertion(id=2, tenant='1', resource='1', lo='10:30', hi='11:30', status='active', slot=None):
            value = slot or f"tstzrange('2026-01-01 {lo}+00','2026-01-01 {hi}+00','[)')"
            return f"INSERT INTO reservations VALUES ({id},{tenant},{resource},{value},'{status}');"
        def reset():
            a.ok('TRUNCATE reservations;')
            a.ok(insertion(1,lo='10:00',hi='12:00'))
        def case(name, sql, expected):
            reset()
            state, _ = a.query(sql)
            assert state == expected, (name,state,expected)
            cases.append(dict(case=name,sqlstate=state))
        case('overlap_same_resource',insertion(), '23P01')
        case('adjacent_half_open',insertion(lo='12:00',hi='13:00'), '00000')
        case('different_resource',insertion(resource='2'), '00000')
        case('different_tenant',insertion(tenant='2'), '00000')
        case('null_tenant',insertion(tenant='NULL'), '23502')
        case('null_resource',insertion(resource='NULL'), '23502')
        case('null_slot',insertion(slot='NULL'), '23502')
        case('empty_slot',insertion(lo='10:00',hi='10:00'), '23514')
        case('unbounded_slot',insertion(slot="tstzrange(NULL,'2026-01-01 11:00+00','[)')"), '23514')
        case('explicit_infinity',insertion(slot="tstzrange('2026-01-01 10:00+00','infinity','[)')"), '23514')
        case('cancelled_overlap',insertion(status='cancelled'), '00000')
        reset()
        a.ok(insertion(status='cancelled'))
        state, _ = a.query("UPDATE reservations SET status='active' WHERE id=2;")
        assert state == '23P01'
        cases.append(dict(case='reactivate_conflict',sqlstate=state))
        case('reversed_bounds',insertion(lo='12:00',hi='10:00'), '22000')
        reset()
        a.ok(insertion(lo='12:00',hi='14:00'))
        a.ok('BEGIN; SET CONSTRAINTS no_active_overlap DEFERRED;')
        a.ok("UPDATE reservations SET slot=tstzrange('2026-01-01 12:00+00','2026-01-01 14:00+00','[)') WHERE id=1;")
        a.ok("UPDATE reservations SET slot=tstzrange('2026-01-01 10:00+00','2026-01-01 12:00+00','[)') WHERE id=2;")
        a.ok('SET CONSTRAINTS no_active_overlap IMMEDIATE; COMMIT;')
        assert a.ok('SELECT id,extract(hour from lower(slot))::int FROM reservations ORDER BY id;') == ['1|12','2|10']
        cases.append(dict(case='deferred_swap',sqlstate='00000',startHours=[12,10]))
        reset()
        a.ok('BEGIN; SET CONSTRAINTS no_active_overlap DEFERRED;')
        a.ok(insertion())
        state,_=a.query('COMMIT;')
        assert state=='23P01'
        cases.append(dict(case='unresolved_deferred_commit',sqlstate=state,remainingRows=int(a.ok('SELECT count(*) FROM reservations;')[0])))
        # Explicitly observe the competing backend waiting on a transaction lock.
        # The wall clock only bounds the harness; it is not a measured result.
        pid = int(b.ok('SELECT pg_backend_pid();')[0])
        for finish, expected in [('COMMIT','23P01'),('ROLLBACK','00000')]:
            a.ok('TRUNCATE reservations; BEGIN;')
            a.ok(insertion(1,lo='10:00',hi='12:00'))
            with ThreadPoolExecutor(max_workers=1) as executor:
                future = executor.submit(b.query,insertion())
                deadline=time.monotonic()+8
                observed=False
                while time.monotonic()<deadline:
                    waiting=observer.ok(f"SELECT coalesce(bool_or(wait_event_type='Lock' AND state='active'),false) FROM pg_stat_activity WHERE pid={pid};")[0]
                    if waiting=='t':
                        observed=True
                        break
                    if future.done():
                        raise AssertionError('Contender finished before a lock wait was observed')
                assert observed, 'No observed lock wait'
                a.ok(finish+';')
                state,_=future.result(timeout=12)
            assert state==expected
            count=int(a.ok('SELECT count(*) FROM reservations;')[0])
            assert count==1
            cases.append(dict(case='race_owner_'+finish.lower(),waitObserved=True,contenderSqlstate=state,remainingRows=count))
        # Compare interval-bound conventions through actual independent inserts.
        a.ok("CREATE TABLE boundary_probe (slot tstzrange, EXCLUDE USING gist (slot WITH &&));")
        for bounds in ['[)','[]']:
            for hour in range(8,15):
                a.ok('TRUNCATE boundary_probe;')
                a.ok(f"INSERT INTO boundary_probe VALUES (tstzrange('2026-01-01 10:00+00','2026-01-01 12:00+00','{bounds}'));")
                state,_=a.query(f"INSERT INTO boundary_probe VALUES (tstzrange('2026-01-01 {hour:02}:00+00','2026-01-01 {hour+1:02}:00+00','{bounds}'));")
                expected = '23P01' if (10<=hour<12 if bounds=='[)' else 9<=hour<=12) else '00000'
                assert state==expected,(bounds,hour,state)
                probes.append(dict(bounds=bounds,candidateStartHour=hour,candidateEndHour=hour+1,sqlstate=state,accepted=state=='00000'))
        return dict(serverVersion=version,caseCount=len(cases),cases=cases,boundaryProbeCount=len(probes),boundaryProbes=probes,
                    limitations='PostgreSQL17.11 isolated behavioral fixture. No performance, ORM, pooler, partitioning or production workload result.')
    finally:
        for s in [a,b,observer]:
            s.close()


if __name__=='__main__':
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--container',required=True)
    print(json.dumps(run(parser.parse_args().container),indent=2,sort_keys=True))
