"""Read one completed, known JSR preflight run; never starts or modifies a pipeline."""
import json
import pathlib
import re
import sys

ROOT = pathlib.Path(__file__).resolve().parents[4]
sys.path.insert(0, str(ROOT / 'work_store/2026-09-11-diet-photo-record-reuse/execution'))
from yunxiao_cli import api, ORG

run_id = int(sys.argv[1])
base = f'/oapi/v1/flow/organizations/{ORG}/pipelines/5264113'
run = api('GET', f'{base}/runs/{run_id}')
assert run['status'] == 'SUCCESS', run['status']
rows = []
for stage in run['stages']:
    for job in stage['stageInfo']['jobs']:
        assert job['status'] == 'SUCCESS'
        gid = 329119 if '副' in job['name'] else 316592
        detail = json.loads(job['result'])['data']['deployOrderId']
        group = api('GET', f'/oapi/v1/flow/organizations/{ORG}/hostGroups/{gid}')
        assert group['hostNum'] == 1
        sn = group['hostInfos'][0]['machineSn']
        log = api('GET', f'{base}/deploy/{detail["id"]}/machine/{sn}/log')['deployLog']
        begin = log.index('JSR_PREFLIGHT_BEGIN')
        end = log.index('JSR_PREFLIGHT_END', begin)
        evidence = log[begin:end + len('JSR_PREFLIGHT_END')]
        files = dict((name, sha) for sha, name in re.findall(r'^([0-9a-f]{64})  /workspace/wwwroot/zhct_jsr/project/(.+)$', evidence, re.M))
        assert files['application/p/logic/MealOrder.php'] == '089df04e521f98aca802ade3bc51e9c9ab13857894a9c7558a9b73723a5a11fd'
        assert '/dist/ http=200' in evidence and '/p/mealOrder/detail http=200' in evidence
        baseline = json.loads((pathlib.Path(__file__).parent.parent / 'hotfix-baseline.json').read_text())
        original = next(v for v in baseline['nodes'] if v['host_group_id'] == gid)
        for item in original['files']:
            if item['file'] != 'application/p/logic/MealOrder.php':
                assert files[item['file']] == item['production_sha256']
        assert 'd4805ec00a7cea47131a06d6e2a1d3258bd6b28f15938e65ebb8952fd16899e1  /workspace/wwwroot/zhct_jsr/hotfix-backups/' in evidence
        row = {'run_id': run_id, 'host_group_id': gid, 'job_end_time': job['endTime'], 'files': files,
               'health': {'static': 200, 'unauthenticated_order_detail': 200},
               'error_counts': re.findall(r'^(?:error_log_bytes|error_log_lines|php_fatal_or_parse_count)=.*$', evidence, re.M),
               'daily_error_log_present': 'daily_error_log_not_present' not in evidence,
               'backup_hash_verified': True}
        rows.append(row)
        outdir = pathlib.Path(__file__).parent.parent / 'hotfix'
        (outdir / f'observation-{run_id}-{gid}.txt').write_text(evidence + '\n')
(outdir / f'observation-{run_id}.json').write_text(json.dumps(rows, ensure_ascii=False, indent=2))
print(json.dumps([{'run_id': r['run_id'], 'node': r['host_group_id'], 'file_checks': len(r['files']), 'http': r['health'], 'error_counts': r['error_counts'], 'daily_error_log_present': r['daily_error_log_present']} for r in rows], ensure_ascii=False))
