#!/usr/bin/env python3
"""Build server discovery evidence from captured wire results, not source assertions."""
import hashlib
import json
from pathlib import Path

ROOT = Path('/tmp/lead-27840-r1/capture2')
SHAS = {
    'before': 'c6ef3b46ebed34fbefa1706674fe5748254cee18',
    'after': 'e9312167e26f2de6984c604c7f07902e287caa58',
}
RUNS = {
    'R3': ['20261103T043113901802-before-signed-out-modern', '20261103T043113943964-after-signed-out-modern'],
    'R4': ['20261103T043245940228-before-signed-out-old', '20261103T043245989961-after-signed-out-old'],
}

def columns(left, right):
    a, b = left.splitlines(), right.splitlines()
    width = max(map(len, a)) + 3
    return '\n'.join((a[i] if i < len(a) else '').ljust(width) + '| ' + (b[i] if i < len(b) else '')
                     for i in range(max(len(a), len(b))))

summary = {}
for row, names in RUNS.items():
    runs = [ROOT / n for n in names]
    results = [json.loads((r / 'discovery.json').read_text()) for r in runs]
    entries = [r['gitlab'] for r in results]
    same = entries[0] == entries[1]
    auth_same = entries[0]['auth'] == entries[1]['auth']
    summary[row] = {'entireGitLabEntryIdentical': same, 'authIdentical': auth_same}
    status = 'PASS: Before and after carry identical auth status, detail, account, version and availability.' if same else 'DIFFERENCE: Before and after GitLab discovery entries differ. See JSON below.'
    manual = json.loads((ROOT / (row + '-manual.json')).read_text())
    text = [status, '', row + ' server discovery follow-up: all configured hosts signed out',
            'Captured from the real dev server through the same discovery RPC used by web/desktop/mobile.',
            'Fresh empty database per side; T3CODE_DEV_SEED=0; no real T3 database read or copied.',
            'No tracked code edited. No browser or component harness involved.', '']
    for side, run in zip(SHAS, runs):
        sha = SHAS[side]
        text += [f'{side.title()}: [{sha[:10]}](https://git.cafe/pingdotgg/t3code/commit/{sha})',
                 f'Full SHA: {sha}', f'Run: {run}',
                 'Launch: T3CODE_DEV_SEED=0 T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD=0 '
                 f'GLAB_CONFIG_DIR=<private signed-out fixture> PATH=<argv wrapper>:<inherited> vp run dev --home-dir {run}/home']
    text += ['', 'RPC method and exact payload:', json.dumps(results[0]['request'], indent=2),
             'Transport: paired browser session over HTTP, one-use wsTicket, JSON WebSocket /ws?orchestrationProtocol=2.',
             'Pairing credentials, session cookies and tickets are omitted.',
             'Below is the GitLab provider entry as returned on the wire, projected to kind/label/executable/status/version/detail/auth.',
             'Option objects are retained verbatim: None means no value; Some.value carries the exact value.',
             'No auth field was redacted, replaced, normalized, or inferred from the Settings UI.', '',
             columns('BEFORE\n' + json.dumps(entries[0], indent=2), 'AFTER\n' + json.dumps(entries[1], indent=2)), '',
             'Exact server argv wrapper logs (manual commands used real binaries directly, so do not appear here):',
             columns('BEFORE\n' + (runs[0] / 'argv.log').read_text(), 'AFTER\n' + (runs[1] / 'argv.log').read_text()), '']
    for side, run in zip(SHAS, runs):
        text += [side.title() + ' wrapper source:', (run / 'bin/glab').read_text()]
    text += ['Redacted configuration shape (same private config directory on both sides):',
             (ROOT / 'signed-out-glab-config-REDACTED.yml').read_text(),
             'Only configured host is gitlab.invalid.example, default host; token deliberately invalid; no gitlab.com credentials.',
             'No ambient GITLAB_TOKEN, GLAB_TOKEN, OAUTH_TOKEN, GITLAB_HOST, GL_HOST, or GLAB_HOST override was present.', '']
    for name in ['version', 'first', 'retry']:
        m = manual[name]
        text += ['Manual command (same GLAB_CONFIG_DIR as the two dev servers):',
                 'GLAB_CONFIG_DIR=<private signed-out fixture> ' + ' '.join(m['argv']),
                 f'Exit code: {m["exitCode"]}', 'stdout BEGIN', m['stdout'], 'stdout END',
                 'stderr BEGIN', m['stderr'], 'stderr END', '']
    if row == 'R4':
        tarball = Path('/tmp/lead-27840-r1/capture/glab-1.78.0.tar.gz')
        binary = Path(manual['version']['argv'][0])
        text += ['Genuine v1.78.0 release binary reused from round 1, no emulated version/flag response.',
                 'Tarball source: https://gitlab.com/gitlab-org/cli/-/releases/v1.78.0/downloads/glab_1.78.0_linux_amd64.tar.gz',
                 'Tarball SHA-256: ' + hashlib.sha256(tarball.read_bytes()).hexdigest(),
                 'Binary SHA-256: ' + hashlib.sha256(binary.read_bytes()).hexdigest(), '']
    if same:
        text += ['Observed result: after-side --all ran; returned discovery auth remains the same first-probe sign-out result.',
                 ('Modern --all also reports signed out.' if row == 'R3' else 'Old glab prints Unknown flag: --all.; that text does not replace auth.detail.'),
                 'Scope: settled discovery only; does not claim proof of retry timeout/stall behavior.']
    (ROOT / (row + '-discovery.txt')).write_text('\n'.join(text) + '\n')
(ROOT / 'comparison.json').write_text(json.dumps(summary, indent=2) + '\n')
print(json.dumps(summary, indent=2))
