"""One disposable, internal-network fixture run using already-present images."""
import json
from pathlib import Path
import subprocess
import sys
import time

RUN=Path(__file__).resolve().parent
REPO=Path('/workspace/contextra-analytics-runtime-lifecycle-refactor')
name='ct-data-fixture-'+str(time.time_ns());pg=name.replace('fixture','pg');redis=name.replace('fixture','redis')
def cmd(args,timeout=30):return subprocess.check_output(args,text=True,stderr=subprocess.STDOUT,timeout=timeout)
roles={}
for row in json.loads(cmd(['docker','inspect',*cmd(['docker','ps','-aq','--filter','label=com.docker.compose.project=contextra']).split()])):
    roles[row['Config']['Labels']['com.docker.compose.service']]=row['Image']
created=[]
try:
    cmd(['docker','network','create','--internal','--label','ct.fixture='+name,name])
    for cname,image,env,command in (
        (pg,roles['postgresql'],['-e','POSTGRES_PASSWORD=fixture-only','-e','POSTGRES_DB=ctfixture'],[]),
        (redis,roles['redis'],[],['redis-server','--save','','--appendonly','no'])):
        cmd(['docker','run','-d','--name',cname,'--pull=never','--network',name,'--cpus=1','--memory=512m',
             '--label','ct.fixture='+name,*env,image,*command]);created.append(cname)
    for _ in range(40):
        if subprocess.run(['docker','exec',pg,'pg_isready','-U','postgres','-d','ctfixture'],capture_output=True).returncode==0:break
        time.sleep(.5)
    else:raise RuntimeError('FIXTURE_DB_NOT_READY')
    runner=name+'-runner';created.append(runner)
    command=['docker','run','--name',runner,'--pull=never','--network',name,'--cpus=2','--memory=2g','--pids-limit=192',
        '--label','ct.fixture='+name,'--entrypoint','python3','--workdir','/opt/contextra',
        '--mount','type=bind,src='+str(REPO)+',dst=/opt/contextra,readonly',
        '--tmpfs','/tmp:rw,size=256m','-e','CT_DATA_FIXTURE=1','-e','OPENBLAS_NUM_THREADS=1',
        '-e','DATABASE_URL=postgresql://postgres:fixture-only@'+pg+':5432/ctfixture',
        '-e','CONTEXTRA_METADATA_REDIS_URL=redis://'+redis+':6379/0',
        roles['analytics'],'-B','-m','unittest',*(sys.argv[1:] or ['discover','-s','tools/icerti_offline/maintenance','-p','test_data_integration.py']),'-v']
    r=subprocess.run(command,capture_output=True,text=True,timeout=180)
    (RUN/('integration-'+str(time.time_ns())+'.log')).write_text(r.stdout+r.stderr);print(r.stdout+r.stderr)
    if r.returncode:raise RuntimeError('INTEGRATION_FAILED')
finally:
    for cname in reversed(created):
        check=subprocess.run(['docker','inspect',cname],capture_output=True,text=True,timeout=10)
        if check.returncode==0:
            row=json.loads(check.stdout)[0]
            assert row['Config'].get('Labels',{}).get('ct.fixture')==name
            cmd(['docker','rm','-f','-v',cname])
    subprocess.run(['docker','network','rm',name],capture_output=True,timeout=15)
