from __future__ import annotations

import copy
import json
from pathlib import Path

import numpy as np
import pytest

from pallet.structure_attributes import aggregate, enrich_targets, validate_policy, validate_rechecks, validate_results
from pallet.structure_mask_fallback import combine_evidence, select_front_faces
from pallet.structure_projection import analyze_measured_mask, analyze_target, consensus, deskew, runs


@pytest.fixture
def policy():
    return json.loads((Path(__file__).parents[1]/'configs/pallet_structure_attributes_v1.json').read_text())


def panel(legs=3, closed=False):
    h, w = 60, 260
    mask = np.zeros((h, w), bool)
    mask[2:12] = True
    for x in np.linspace(0, w-18, legs).astype(int):
        mask[2:, x:x+18] = True
    if closed:
        mask[-8:] = True
    image = np.full((h+20, w+20), 60, np.uint8)
    image[10:10+h, 10:10+w][mask] = 235
    row = {'target_id': 'a', 'target_key': 'key', 'bbox': {'x': 10., 'y': 10., 'width': float(w), 'height': float(h)},
           'crop_touches_image_edge': False, 'final_class_id': 1, 'final_class': 'Class 1'}
    return image, row, mask


@pytest.mark.parametrize('legs', [2, 3])
@pytest.mark.parametrize('closed', [False, True])
def test_clean_intensity_panels_have_expected_independent_attributes(policy, legs, closed):
    image, row, _ = panel(legs, closed)
    result = analyze_target(image, row, policy, include_mask=True)
    assert result['support_leg_count'] == legs
    assert result['closure_type'] == ('tian' if closed else 'chuan')
    assert result['_raw_threshold_mask'].shape == (60, 260)
    assert result['_binary_mask'].shape == (60, 260)
    assert result['leg_consensus']['agreeing_thresholds'] >= 4


def test_four_peaks_require_recheck_not_automatic_physical_four_leg_claim(policy):
    image, row, _ = panel(4)
    result = analyze_target(image, row, policy)
    assert result['support_leg_count'] is None
    assert result['leg_consensus']['candidate'] == 4
    assert 'four_leg_candidate_review' in result['flags']


@pytest.mark.parametrize('flag', ['truncated', 'low_intensity_contrast', 'upper_edge_only'])
def test_invisible_or_truncated_face_is_not_forced_into_six_classes(policy, flag):
    image, row, _ = panel(3)
    if flag == 'truncated': row['crop_touches_image_edge'] = True
    elif flag == 'low_intensity_contrast': image[:] = 200
    else: row['bbox']['height'] = 10.
    result = analyze_target(image, row, policy)
    assert result['support_leg_count'] is None and result['closure_type'] is None
    assert flag in result['flags']


def test_unknown_trials_are_in_consensus_denominator(policy):
    trials = [{'value': 3}, {'value': 3}, {'value': 3}, {'value': None}, {'value': None}]
    value, evidence = consensus(trials, 'value', policy)
    assert value is None and evidence['agreement'] == .6


def test_mask_projection_distinguishes_background_returns_from_missing_points(policy):
    image, row, mask = panel(3)
    full = np.zeros_like(image, bool); full[10:70, 10:270] = mask
    valid = np.ones_like(full)
    result = analyze_measured_mask(full, valid, row, policy)
    assert result['support_leg_count'] == 3 and result['closure_type'] == 'chuan'
    missing = analyze_measured_mask(full, full, row, policy)
    assert missing['closure_type'] is None
    assert 'missing_returns_not_an_opening' in missing['flags']
    assert result['source_masks_filled'] is False


def test_mask_projection_preserves_closed_beam(policy):
    image, row, mask = panel(3, True)
    full = np.zeros_like(image, bool); full[10:70, 10:270] = mask
    result = analyze_measured_mask(full, np.ones_like(full), row, policy)
    assert result['support_leg_count'] == 3 and result['closure_type'] == 'tian'


def test_empty_measured_mask_is_unresolved_not_a_negative(policy):
    image, row, _ = panel()
    full = np.zeros_like(image, bool)
    result = analyze_measured_mask(full, np.ones_like(full), row, policy)
    assert result['support_leg_count'] is None and result['closure_type'] is None
    assert result['review_required'] and 'measured_mask_too_sparse' in result['flags']


def test_html_json_preserves_identity_and_escapes_script_end():
    from pallet.structure_attribute_report import json_script
    original = {'id': 'sample</script>托盘'}
    encoded = json_script(original)
    assert '</script>' not in encoded
    assert json.loads(encoded) == original


def test_offline_gallery_data_decoder_checks_group_and_resource_layout(tmp_path):
    from scripts.verify_structure_attributes import decode_gallery
    page = tmp_path/'gallery.html'
    page.write_text('<script>const rows=[{"target_id":"a"}],groups=[{"final_class_id":1}],roots={"dataset":"../data"},$=x=>x;</script>')
    rows, groups, roots = decode_gallery(page)
    assert rows == [{'target_id': 'a'}] and groups == [{'final_class_id': 1}]
    assert roots['dataset'] == '../data'


def test_structure_exports_protect_existing_human_edits(tmp_path):
    from pallet.fork_face_anylabeling import protected_write
    path = tmp_path/'targets.csv'
    protected_write(path, b'original\n')
    protected_write(path, b'original\n')
    path.write_bytes(b'human edit\n')
    with pytest.raises(ValueError, match='human edits'):
        protected_write(path, b'original\n')
    assert path.read_bytes() == b'human edit\n'


def face(fid=1, points=1000, normal=(1., 0., 0.), offset=1000., view=.98, vertical=.1):
    return {'status': 'selected_candidate', 'mask_points': points, 'face_id': fid, 'face_key': f'f{fid}',
            'view_normal_cosine': view, 'image_vertical_normal_cosine': vertical,
            'plane': [*normal, offset], 'tolerance': 3., 'median_range': 1100.}


def test_front_panel_merges_only_coplanar_fragments_not_back_or_horizontal_face(policy):
    faces = [face(), face(2, 80, offset=1004.), face(3, 90, offset=1080.),
             face(4, 900, normal=(0., 1., 0.), view=.3, vertical=.95)]
    selected, flags = select_front_faces(faces, policy)
    assert [f['face_id'] for f in selected] == [1, 2]
    assert not flags


def test_front_plane_sign_is_not_semantic_difference(policy):
    selected, _ = select_front_faces([face(), face(2, 80, normal=(-1., 0., 0.), offset=-1000.)], policy)
    assert len(selected) == 2


def test_equal_different_visible_planes_are_ambiguous(policy):
    _, flags = select_front_faces([face(), face(2, 990, normal=(.8, 0., .6))], policy)
    assert 'ambiguous_primary_front_plane' in flags


def evidence(legs=3, closure=None, flags=None):
    return {'support_leg_count': legs, 'closure_type': closure, 'review_required': closure is None,
            'flags': flags or ['unstable'], 'selected_trial': {}, 'leg_consensus': {}, 'closure_consensus': {},
            'attribute_sources': {'support_leg_count': 'intensity_projections', 'closure_type': 'unknown'},
            'pointcloud_fallback_attempted': False}


def test_fallback_fills_only_unknown_attributes_and_keeps_both_sources():
    intensity = evidence(3, None)
    measured = evidence(3, 'tian', [])
    combined = combine_evidence(intensity, measured)
    assert (combined['support_leg_count'], combined['closure_type']) == (3, 'tian')
    assert combined['attribute_sources']['closure_type'] == 'pointcloud_front_mask_projections'
    assert combined['intensity_evidence'] == intensity
    assert combined['pointcloud_evidence'] == measured


def test_modal_conflict_remains_unknown_not_silently_overwritten():
    combined = combine_evidence(evidence(2, None), evidence(3, 'tian'))
    assert combined['support_leg_count'] is None and combined['closure_type'] == 'tian'
    assert 'intensity_pointcloud_support_leg_count_conflict' in combined['flags']


def test_partial_attributes_and_old_group_fields_survive_export():
    _, row, _ = panel()
    old = copy.deepcopy(row)
    result = evidence(3)
    output = enrich_targets([row], {'a': result}, {'a'}, {})
    validate_results([row], output, {})
    assert row == old
    assert output[0]['structure_label'] is None
    assert output[0]['structure_attribute_state'] == 'partial'
    assert output[0]['final_class_id'] == row['final_class_id']
    assert output[0]['structure_training_eligible'] is False
    summary, groups = aggregate(output)
    assert summary['total_targets'] == 1 and groups[0]['partial'] == 1


def test_visual_recheck_must_be_necessary_unique_and_source_bound():
    _, row, _ = panel()
    document = {'kind': 'assistant_necessary_projection_rechecks', 'human_reviewed': False,
                'source_targets_sha256': 'abc', 'observations': [
                    {'target_key': 'key', 'support_leg_count': 3, 'closure_type': 'chuan',
                     'evidence': '当前面左右与中部三支撑均清楚，下部开口未见横梁且底部可见。'}]}
    assert len(validate_rechecks(document, [row], {'a': evidence()}, 'abc')) == 1
    with pytest.raises(ValueError, match='exact frozen source'):
        validate_rechecks(document, [row], {'a': evidence()}, 'changed')
    with pytest.raises(ValueError, match='limited'):
        validate_rechecks(document, [row], {'a': {'review_required': False}}, 'abc')


def test_result_validation_rejects_changed_original_and_false_human_review():
    _, row, _ = panel()
    out = enrich_targets([row], {'a': evidence()}, set(), {})
    changed = copy.deepcopy(out); changed[0]['final_class_id'] = 22
    with pytest.raises(ValueError, match='Original'):
        validate_results([row], changed, {})
    changed = copy.deepcopy(out); changed[0]['structure_human_reviewed'] = True
    with pytest.raises(ValueError, match='human-confirmed'):
        validate_results([row], changed, {})


@pytest.mark.parametrize('key,value', [('threshold_offsets', [0, 0, 8]), ('minimum_threshold_agreement', 0.4),
                                     ('pointcloud_fallback', False), ('support_leg_counts', [3, 4])])
def test_invalid_projection_policy_rejected(policy, key, value):
    policy[key] = value
    with pytest.raises(ValueError): validate_policy(policy)


def test_runs_and_deskew_have_explicit_invalid_pixels():
    assert runs([True, True, False, True]) == [(0, 2), (3, 4)]
    mask = np.ones((8, 20), bool)
    shifted, valid = deskew(mask, .5)
    assert not valid.all() and not shifted[~valid].any()
