#!/usr/bin/env python3
"""Attach runtime trace observations, never promote observations to test passes."""
import csv
from collections import Counter
import json
from pathlib import Path

HERE = Path(__file__).resolve().parent

def main():
    runtime = {lane: json.loads((HERE / f'store-runtime-{lane}.json').read_text()) for lane in ('B', 'C')}
    with (HERE / 'inventory-20261010.csv').open() as source:
        rows = [r for r in csv.DictReader(source) if r['repo'] == 'store']
    by_line = Counter((r['relative_file'], r['line']) for r in rows)
    states = Counter()
    terminal_states = Counter()
    observed = []
    for row in rows:
        site = row['relative_file'] + ':' + row['line']
        hits, drifts = [], []
        for lane, trace in runtime.items():
            if site not in trace['callsites']:
                continue
            if trace['source_hashes'].get(row['relative_file']) != row['source_sha256']:
                drifts.append(lane)
            else:
                hits.append(lane)
        state = ('source_unverified_or_drift' if drifts else
                 'dual_trace_candidate' if len(hits) == 2 else
                 'single_trace_candidate' if hits else 'not_observed')
        if hits and by_line[(row['relative_file'], row['line'])] > 1:
            state += '_same_line_ambiguous'
        states[state] += 1
        if row['phase'] == 'execution_candidate':
            terminal_states[state] += 1
        if hits or drifts:
            observed.append({k: row[k] for k in ('callsite_id', 'relative_file', 'line', 'column',
                'method', 'phase', 'operation', 'call_kind')} | {'trace_state': state, 'lanes': hits})
    known_sites = {r['relative_file'] + ':' + r['line'] for r in rows}
    summary = {'repo': 'store', 'candidate_states': dict(states),
        'execution_candidate_states': dict(terminal_states),
        'observed_candidates': observed,
        'unmapped_runtime_locations': {lane: sorted(set(t['callsites']) - known_sites) for lane, t in runtime.items()},
        'compatibility_passes_inferred': 0,
        'limits': ['Trace locations include wrappers/callers, not only actual SQL terminal calls.',
                   'Same-line candidates cannot be resolved without a column-aware execution probe.',
                   'Statement fingerprints differ by dialect and metadata; do not assert equality.',
                   'No SQL listener proof for raw PDO, failed SQL, commit/rollback or cache-hit branches.',
                   'Static candidates are not a reliable denominator for a compatibility percentage.']}
    (HERE / 'store-runtime-linked.json').write_text(json.dumps(summary, ensure_ascii=False, indent=2) + '\n')
    print(json.dumps({k: v for k, v in summary.items() if k not in ('observed_candidates', 'unmapped_runtime_locations')}, ensure_ascii=False))

if __name__ == '__main__':
    main()
