import os,sys,re,json,subprocess,pathlib,datetime,yaml
root=pathlib.Path(__file__).resolve().parent
run=root/datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ');run.mkdir()
results=[]
for side,checkout in [('before',sys.argv[1]),('after',sys.argv[2])]:
    checkout=pathlib.Path(checkout).resolve()
    sha=subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip()
    workflow=yaml.safe_load((checkout/'.github/workflows/release.yml').read_text())
    steps=next(j['steps'] for j in workflow['jobs'].values() if any(s.get('name')=='Resolve release asset list' for s in j.get('steps',[])))
    selected=[s for s in steps if s.get('name') in ['Merge macOS updater manifests','Merge Windows updater manifests','Merge desktop updater manifests','Resolve release asset list']]
    transcript=[f'{side.upper()} | commit {sha}','Environment: Linux; workflow Bash steps and real Node CLI; synthetic release artifacts.','No publish/API step executed. Exit status controls whether publication can be reached.','']
    for channel in ['latest','nightly']:
      for missing in [None,'win-arm64','win-x64','mac-arm64','mac-x64']:
        case=f'{channel} / '+('complete' if missing is None else 'missing '+missing)
        folder=run/side/channel/('complete' if missing is None else missing);folder.mkdir(parents=True)
        assets=folder/'release-assets';assets.mkdir()
        for platform in ['mac','win']:
          for arch in ['arm64','x64']:
            if missing==f'{platform}-{arch}':continue
            name=f'{channel}-mac.yml' if platform=='mac' and arch=='arm64' else f'{channel}-{platform}-{arch}.yml'
            url=f'T3-Code-0.9.0-{arch}.'+('zip' if platform=='mac' else 'exe')
            (assets/name).write_text(f'version: 0.9.0\nfiles:\n  - url: {url}\n    sha512: synthetic-checksum\n    size: 123\npath: {url}\nsha512: synthetic-checksum\nreleaseDate: 2026-11-14T00:00:00.000Z\n')
        transcript.extend([f'=== {case} ===','Inputs: '+', '.join(p.name for p in sorted(assets.iterdir()))])
        exitcode=0
        for step in selected:
          script=step['run'].replace('release-assets',str(assets))
          script=re.sub(r'\$\{\{ needs.preflight.outputs.release_channel \}\}', 'stable' if channel=='latest' else 'nightly',script)
          script=re.sub(r'\$\{\{ steps.android_apk.outcome \}\}','skipped',script)
          p=subprocess.run(['bash','--noprofile','--norc','-eo','pipefail','-c',script],cwd=checkout,text=True,capture_output=True,env={**os.environ,'GITHUB_OUTPUT':str(folder/'github-output'),'RUNNER_TEMP':str(folder),'NO_COLOR':'1'})
          transcript.append(f"{step['name']}: exit {p.returncode}")
          raw=p.stdout+p.stderr
          raw=raw.replace(str(checkout),'<checkout>').replace(str(root),'<evidence>')
          (folder/(re.sub('[^a-zA-Z]+','-',step['name'])+'.log')).write_text(raw)
          if raw:transcript.append(raw.strip())
          if p.returncode:exitcode=p.returncode;break
        if not exitcode:
          transcript.append('Publication gate: REACHED asset list')
          transcript.append('Upload manifest matches: '+', '.join(p.name for p in sorted(assets.glob('*.yml'))))
          for name in [f'{channel}-mac.yml',f'{channel}.yml']:
            p=assets/name
            transcript.append(name+': '+(', '.join(re.findall(r'  - url: (.+)',p.read_text())) if p.exists() else 'ABSENT'))
        else:transcript.append('Publication gate: BLOCKED before asset list')
        transcript.append('')
        results.append(dict(side=side,channel=channel,missing=missing,exit=exitcode))
    (run/f'{side}.txt').write_text('\n'.join(transcript)+'\n')
(run/'results.json').write_text(json.dumps(results,indent=2))
print(run)
print(json.dumps(results,indent=2))
