"""Disjoint installed qualification batches; commands, counts and payload retained."""
import argparse
from concurrent.futures import ThreadPoolExecutor
import hashlib
import json
import os
from pathlib import Path
import subprocess
import time

p=argparse.ArgumentParser();p.add_argument('--tools',type=Path,required=True);p.add_argument('--output',type=Path,required=True)
a=p.parse_args();root=Path(__file__).resolve().parents[1];a.output=a.output.resolve();a.output.mkdir(parents=True,exist_ok=True)
tools=a.tools.resolve(); env={**os.environ,
 'PYCFORGE_TEST_ENGINE':str(tools/'venv-engine/bin/python'),
 'PYCFORGE_TEST_OLD_ENGINE':str(tools/'engine-1.3.60/bin/python'),
 'PYCFORGE_LEGACY_ENGINE':str(tools/'engine-1.3.61/bin/python'),
 'PYCFORGE_PREVIOUS_ENGINE':str(tools/'engine-1.3.61/bin/python'),
 'PCFC11_PATH':str(tools/'pcfc11/current/PCFC11-0.2.42/pcfc11'),
 'PCFC11_LINUX_CC':'/usr/bin/gcc','QT_QPA_PLATFORM':'offscreen'}
env.pop('PYTHONPATH',None)
groups={
 'headless-arrays':['tests/test_array_workflow.py'],
 'headless-authoring':['tests/'+n for n in ['test_scalar_contracts_v2.py','test_scalar_parameters_v3.py','test_template_customization.py','test_value_workflow.py']],
 'headless-readiness':['tests/test_readiness_and_editing.py','tests/test_workflow.py'],
 'headless-fixtures':['tests/test_fixture_authoring.py','tests/test_fixture_results.py','tests/test_source_repair.py'],
 'gui-native':['tests_gui/test_desktop.py','tests_gui/test_preflight_ui.py']}
used={n for v in groups.values() for n in v}
groups['headless-core']=[str(f.relative_to(root)) for f in sorted((root/'tests').glob('test_*.py')) if str(f.relative_to(root)) not in used]
groups['gui-workspace']=[str(f.relative_to(root)) for f in sorted((root/'tests_gui').glob('test_*.py')) if str(f.relative_to(root)) not in used]
payload={str(f.relative_to(root/'src')):hashlib.sha256(f.read_bytes()).hexdigest()
         for f in sorted((root/'src/pycforge_sdk').rglob('*')) if f.is_file() and '__pycache__' not in f.parts}
(a.output/'frozen-product.json').write_text(json.dumps(payload,indent=2)+'\n')
commands=[]
for name,files in groups.items():
 python=tools/('venv-gui' if name.startswith('gui') else 'venv-headless')/'bin/python'
 cmd=[str(python),str(root/'tools/run_qualified_tests.py'),str(a.output/(name+'-accounting.json')),
      *files,'-vv','--tb=short','-o','faulthandler_timeout=90','--junitxml='+str(a.output/(name+'.xml'))]
 commands.append({'name':name,'argv':cmd,'cwd':str(root),
                  'env':{k:v for k,v in env.items() if k.startswith('PYCFORGE_') or k in ('PCFC11_PATH','PCFC11_LINUX_CC','QT_QPA_PLATFORM')}})
(a.output/'commands.json').write_text(json.dumps(commands,indent=2)+'\n')
def run(command):
 name=command['name'];started=time.monotonic()
 with (a.output/(name+'.log')).open('w') as out:
  try: code=subprocess.run(command['argv'],cwd=root,env=env,stdout=out,stderr=subprocess.STDOUT,timeout=900).returncode
  except subprocess.TimeoutExpired:code=124
 result={'name':name,'exit_code':code,'seconds':round(time.monotonic()-started,3)}
 print(json.dumps(result),flush=True);return result
with ThreadPoolExecutor(max_workers=3) as pool: results=list(pool.map(run,commands))
all_nodes=[]
for row in results:
 path=a.output/(row['name']+'-accounting.json')
 if path.exists():
  data=json.loads(path.read_text());calls=[r for r in data['reports'] if r['when']=='call']
  row['collected']=len(data['collected']);row['passed']=sum(r['outcome']=='passed' for r in calls)
  row['complete']=sorted(r['nodeid'] for r in calls)==sorted(data['collected'])
  all_nodes.extend(data['collected'])
(a.output/'qualification-summary.json').write_text(json.dumps(results,indent=2)+'\n')
assert len(all_nodes)==len(set(all_nodes))
assert all(r['exit_code']==0 and r.get('complete') and r.get('passed')==r.get('collected') for r in results),results
print('All collected tests completed and passed exactly once:',len(all_nodes),flush=True)
