"""Original-box full point cloud input; automatic face is only an optional anchor."""
import argparse
import fcntl
import json
from pathlib import Path

import numpy as np

from .cluster_targets import load_dataset
from .pose_benchmark import ROOT, SOURCE, sha, read_rows
from .pose_refinement import atomic_json, feature_values
from .pose_review_geometry import GeometryEngine, canonical, raster_mask
from .fork_geometry import valid_xyz


def prepare(split='train'):
    ROOT.mkdir(exist_ok=True)
    with (ROOT / ('roi_' + split + '.lock')).open('a') as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)
        return _prepare(split)


def _prepare(split):
    formal = Path(json.loads(Path('configs/active_formal_dataset.json').read_text())['dataset'])
    _, sources = load_dataset(formal)
    engine = GeometryEngine(formal, ROOT / 'roi_registration')
    rows = [r for r in read_rows(SOURCE / 'snapshot/eligible.jsonl') if r['split'] == split]
    results = []
    for i, row in enumerate(rows):
        key = row['target_key']
        dest = ROOT / 'roi_features' / (key + '.npz')
        if dest.exists():
            results.append(json.loads(dest.with_suffix('.json').read_text()))
            continue
        source = sources[row['frame_id']]
        try:
            points, mapping = engine.registered(canonical(source).decode())
            b = row['bbox']; x, y, w, h = (b[k] for k in ('x', 'y', 'width', 'height'))
            mask = raster_mask([[x, y], [x + w, y], [x + w, y + h], [x, y + h]], *source['size'])
            yy, xx = np.nonzero(mask)
            ids = mapping[yy, xx]
            good = valid_xyz(points[ids, :3])
            ids, uv = ids[good], np.column_stack((xx, yy))[good]
            if len(ids) < 16:
                raise ValueError('fewer_than_16_valid_ROI_points')
            xyzi = points[ids].astype(float)
            scale_mm = source['sensor_policy'].get('scale_to_mm')
            scale = scale_mm / 1000 if scale_mm is not None else None
            # The frozen label sensor policy is only used to verify source units.
            if scale != row['sensor']['scale_to_m']:
                raise ValueError('source_unit_policy_mismatch')
            if scale is not None:
                xyzi[:, :3] *= scale
            old = SOURCE / 'cache/features' / (key + '.npz')
            if old.exists():
                with np.load(old) as z:
                    base, width, direction = z['base'], float(z['width']), z['direction']
                    globals_ = z['globals'].copy()
                anchor = 'automatic_face_optional'
            else:
                base = np.median(xyzi[:, :3], axis=0)
                width = max(float(np.quantile(xyzi[:, 1], .99) - np.quantile(xyzi[:, 1], .01)), 1e-8)
                direction = np.array([1., 0.])
                globals_ = None
                anchor = 'roi_median_source_forward_fallback'
            basis = np.column_stack(([-direction[1], direction[0], 0], [*direction, 0], [0, 0, 1]))
            candidate = dict(center=base, half_width=width / 2, basis=basis)
            fs, gs = [], []
            for variant in range(3):
                f, g, _, _, _ = feature_values(xyzi, uv, source['size'], b, candidate, 42 + variant, 512)
                fs.append(f); gs.append(g)
            # Absolute-ROI point inputs retain the v2 decoding reference for fair paired CV.
            dest.parent.mkdir(parents=True, exist_ok=True)
            np.savez_compressed(dest, features=np.stack(fs), globals=np.stack(gs) if globals_ is None else globals_,
                                base=base, width=width, direction=direction)
            result = dict(target_key=key, state='complete', split=split, sha256=sha(dest),
                          input='all_valid_original_bbox_points_with_1pct_outlier_trim', anchor=anchor,
                          roi_points=len(ids), source_pcd_sha256=source['source_anchor_hash'])
            atomic_json(dest.with_suffix('.json'), result)
        except ValueError as exc:
            result = dict(target_key=key, state='failed', reason=str(exc), split=split)
        results.append(result)
        if i % 100 == 0:
            print(json.dumps(dict(stage='roi', split=split, completed=i + 1, total=len(rows))), flush=True)
    atomic_json(ROOT / ('roi_' + split + '.json'), results)
    return results


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--split', choices=['train', 'val', 'test'], default='train')
    prepare(parser.parse_args().split)
