"""Select a measured front plane, excluding other faces and rear returns."""
from __future__ import annotations

import math
from pathlib import Path

import cv2
import numpy as np

from pallet.fork_face_anylabeling import digest, safe_path
from pallet.merge_appearance_classes import read_json, read_jsonl
from pallet.structure_projection import analyze_measured_mask


def select_front_faces(faces, policy):
    candidates = [f for f in faces if f['status'] == 'selected_candidate' and f.get('mask_points', 0) >= 32
                  and f.get('view_normal_cosine', 0) >= policy['minimum_face_view_cosine']
                  and f.get('image_vertical_normal_cosine', 1) <= policy['maximum_face_vertical_cosine']]
    if not candidates:
        return [], ['no_credible_front_plane']
    ranked = sorted(candidates, key=lambda f: (-f['mask_points']*f['view_normal_cosine']**2, f['face_id']))
    anchor = ranked[0]
    selected = []
    n1 = np.asarray(anchor['plane'][:3], float)
    n1 /= np.linalg.norm(n1)
    flags = []
    for face in ranked:
        n2 = np.asarray(face['plane'][:3], float)
        n2 /= np.linalg.norm(n2)
        dot = float(n1@n2)
        angle = math.degrees(math.acos(float(np.clip(abs(dot), 0, 1))))
        offset = abs(anchor['plane'][3]-(face['plane'][3] if dot >= 0 else -face['plane'][3]))
        tolerance = max(2*anchor['tolerance'], 2*face['tolerance'],
                        policy['coplanar_range_fraction']*anchor['median_range'])
        if angle <= policy['coplanar_angle_degrees'] and offset <= tolerance:
            selected.append(face)
        elif (face['mask_points']*face['view_normal_cosine']**2 >= .85*anchor['mask_points']*anchor['view_normal_cosine']**2
              and angle > 15):
            flags.append('ambiguous_primary_front_plane')
    return selected, flags


class MeasuredFrontMasks:
    def __init__(self, root, rows, inputs):
        self.root = Path(root).resolve()
        self.used_assets = {}
        self.export = read_json(self.root/'export_manifest.json')
        receipt_path = self.root.parent/'delivery_manifest.json'
        receipt = read_json(receipt_path)
        if digest(self.root/'export_manifest.json') != receipt['validation']['final_export_manifest_sha256']:
            raise ValueError('Measured mask export does not match its completed delivery')
        for name in ('faces.jsonl', 'targets.jsonl', 'frames.jsonl'):
            path = self.root/name
            if digest(path) != self.export['files'][name]:
                raise ValueError(f'Measured mask source changed: {name}')
            inputs[str(path)] = digest(path)
        inputs[str(self.root/'export_manifest.json')] = digest(self.root/'export_manifest.json')
        inputs[str(receipt_path)] = digest(receipt_path)
        targets = {r['target_id']: r for r in read_jsonl(self.root/'targets.jsonl')}
        if set(targets) != {r['target_id'] for r in rows}:
            raise ValueError('Measured masks and formal target identities disagree')
        for row in rows:
            target = targets[row['target_id']]
            if any(target[k] != row[k] for k in ('bbox', 'frame_id', 'split', 'group_id')):
                raise ValueError('Measured mask native identity / geometry changed')
        self.faces = {}
        for face in read_jsonl(self.root/'faces.jsonl'):
            if face['status'] == 'selected_candidate':
                self.faces.setdefault(face['target_id'], []).append(face)
        self.frames = {r['frame_id']: r for r in read_jsonl(self.root/'frames.jsonl')}

    def frame_arrays(self, frame_id):
        row = self.frames[frame_id]
        paths = [row['instances'], row['cloud']]
        hashes = {}
        for name in paths:
            path = safe_path(self.root, name)
            expected = self.export['files'][name]
            if digest(path) != expected:
                raise ValueError(f'Measured front-mask asset changed: {name}')
            hashes[name] = expected
        self.used_assets.update(hashes)
        instances = cv2.imread(str(safe_path(self.root, row['instances'])), cv2.IMREAD_UNCHANGED)
        if instances is None or instances.dtype != np.uint16:
            raise ValueError('Invalid native measured face ID image')
        with np.load(safe_path(self.root, row['cloud']), allow_pickle=False) as archive:
            uv, parent = archive['uv'], archive['parent_box_index']
        if uv.shape != (len(parent), 2) or (uv < 0).any() or (uv[:, 0] >= instances.shape[1]).any() or (uv[:, 1] >= instances.shape[0]).any():
            raise ValueError('Invalid measured point-to-pixel mapping')
        return instances, uv, parent, hashes

    def analyze(self, row, arrays, policy):
        instances, uv, parent, hashes = arrays
        faces, flags = select_front_faces(self.faces.get(row['target_id'], []), policy)
        chosen = [f['face_id'] for f in faces]
        raw_mask = np.isin(instances, chosen) if chosen else np.zeros_like(instances, bool)
        if int(raw_mask.sum()) != sum(f['mask_points'] for f in faces):
            raise ValueError('Measured front pixels disagree with frozen face records')
        validity = np.zeros_like(instances, bool)
        points = uv[parent == row['box_index']]
        validity[points[:, 1], points[:, 0]] = True
        evidence = analyze_measured_mask(raw_mask, validity, row, policy)
        evidence['flags'] = sorted(set(evidence['flags']+flags))
        if flags:
            evidence['support_leg_count'] = evidence['closure_type'] = None
        evidence['review_required'] = bool(evidence['flags'])
        evidence['source_front_faces'] = [f['face_key'] for f in faces]
        evidence['source_front_face_ids'] = chosen
        evidence['source_assets'] = hashes
        evidence['front_face_semantics_human_confirmed'] = False
        return evidence, raw_mask


def combine_evidence(intensity, measured):
    combined = dict(intensity)
    chosen_from_mask = False
    conflicts = []
    sources = {}
    for key in ('support_leg_count', 'closure_type'):
        old, new = intensity[key], measured[key]
        if old is not None and new is not None and old != new:
            combined[key] = None
            conflicts.append('intensity_pointcloud_'+key+'_conflict')
            sources[key] = 'conflict_unknown'
        elif old is None and new is not None:
            combined[key] = new
            sources[key] = 'pointcloud_front_mask_projections'
            chosen_from_mask = True
        else:
            sources[key] = 'intensity_projections' if old is not None else 'unknown'
    combined['intensity_evidence'] = intensity
    combined['pointcloud_evidence'] = measured
    combined['pointcloud_fallback_attempted'] = True
    combined['attribute_sources'] = sources
    combined['method'] = 'intensity_then_measured_front_mask_projections'
    combined['flags'] = sorted(set(conflicts + ([] if all(combined[k] is not None for k in sources) else
        intensity['flags']+measured['flags'])))
    combined['review_required'] = bool(combined['flags']) or any(combined[k] is None for k in sources)
    combined['projection_plot_source'] = 'pointcloud_front_mask' if chosen_from_mask else 'intensity'
    if chosen_from_mask:
        for key in ('selected_trial', 'leg_consensus', 'closure_consensus'):
            combined[key] = measured[key]
    return combined
