"""Density plan T0 sampler fingerprint (PLAN-final.md "T0 sampler validation contract"), loaded via PYTHONPATH.
Leaves the frozen code untouched: when the fitter's `tracks` module is imported, its _sample_prepared_track_points is
wrapped so that the FIRST call writes $DENSITY_TRACK_HASH_OUT (JSON: sha256 per array of the prepared track pool and
of the resampled bundle, track count, effective k, workload k*sum(p_i*L_i)). If $DENSITY_TRACK_HASH_REF names an
existing file whose combined hash differs, the fit aborts (SystemExit 3) before its first track loss.
Inactive unless DENSITY_TRACK_HASH_OUT is set."""
import importlib.abc, importlib.machinery, os, sys

OUT = os.environ.get('DENSITY_TRACK_HASH_OUT')
SKIP = {'device', 'staging', 'resampled_cache', 'offsets', 'lengths', 'sampling_probabilities', 'device_points',
        'flat_zyx_device'}


def _digest(obj, out, path):
    import hashlib, numpy as np, torch
    if isinstance(obj, dict):
        for k in sorted(obj, key=str):
            if k in SKIP or str(k).endswith('_device'):
                continue
            _digest(obj[k], out, f'{path}.{k}')
        return
    if isinstance(obj, torch.Tensor):
        obj = obj.detach().cpu().numpy()
    if isinstance(obj, np.ndarray):
        a = np.ascontiguousarray(obj)
        out[path] = f'{a.dtype}{list(a.shape)}:' + hashlib.sha256(a.tobytes()).hexdigest()
    elif isinstance(obj, (int, float, str, bool, list, tuple)) or obj is None:
        out[path] = repr(obj)
    else:
        out[path] = f'<{type(obj).__name__}>'


def _install(mod):
    orig = mod._sample_prepared_track_points
    state = {'done': False}

    def wrapped(prepared, num_tracks_per_step, num_points_per_track, min_sample_spacing=20.0,
                max_sample_spacing=60.0, max_crossings=None):
        if not state['done'] and prepared is not None:
            state['done'] = True
            import hashlib, json, numpy as np
            res = mod._build_resampled_track_bundle(prepared, min_sample_spacing, max_sample_spacing)
            h = {}; _digest(prepared, h, 'prepared'); _digest(res, h, 'resampled')
            n = int(prepared['lengths'].numel()); k = min(int(num_tracks_per_step), n)
            p = prepared.get('sampling_probabilities_cpu')
            L = np.diff(res['offsets'].detach().cpu().numpy())
            work = float(k * np.sum(np.asarray(p) * L)) if p is not None and len(p) == len(L) else None
            combined = hashlib.sha256(json.dumps(h, sort_keys=True).encode()).hexdigest()
            rec = dict(combined=combined, tracks=n, points=int(prepared['offsets_cpu'][-1]), k=k,
                       resampled_points=int(L.sum()), workload=work, arrays=h,
                       spacing=[float(min_sample_spacing), float(max_sample_spacing)])
            json.dump(rec, open(OUT, 'w'), indent=1)
            print(f'DENSITY_TRACK_HASH {combined} tracks {n} k {k} workload {work}', flush=True)
            ref = os.environ.get('DENSITY_TRACK_HASH_REF')
            if ref and os.path.exists(ref) and os.path.realpath(ref) != os.path.realpath(OUT):
                want = json.load(open(ref))['combined']
                if want != combined:
                    print(f'DENSITY_TRACK_HASH MISMATCH vs {ref}: {want}', flush=True)
                    raise SystemExit(3)
                print(f'DENSITY_TRACK_HASH MATCH {ref}', flush=True)
        return orig(prepared, num_tracks_per_step, num_points_per_track, min_sample_spacing, max_sample_spacing,
                    max_crossings)

    mod._sample_prepared_track_points = wrapped


class _Finder(importlib.abc.MetaPathFinder):
    def find_spec(self, name, path, target=None):
        if name != 'tracks':
            return None
        spec = importlib.machinery.PathFinder.find_spec(name, path)
        if spec is None or spec.loader is None:
            return None
        loader = spec.loader
        exec_module = loader.exec_module

        def exec_and_wrap(module):
            exec_module(module)
            _install(module)
        loader.exec_module = exec_and_wrap
        return spec


if OUT:
    sys.meta_path.insert(0, _Finder())
