"""Rejected-quality saves cannot silently become production/GT/quota labels."""
from copy import deepcopy
from pathlib import Path
from types import SimpleNamespace

import pytest

from pallet.mask_gallery_review import MaskReviewStore, ReviewError
from pallet.mask_nonconforming_review import FALSE_FLAGS, SCHEMA, NonconformingEditor, editor_script, sha, validate_target


def proposal():
    return dict(schema=SCHEMA, target_key='a'*24, class_id=19, polygon=[], vertex_count=0,
        source=dict(target_key='a'*24, size=[100, 80], box_index=0), source_quality='nonconforming',
        exception_authorized=True, status='nonconforming_pending_manual_inspection',
        original_rejection_reasons=['脚底不清，先前暂缓'], **dict.fromkeys(FALSE_FLAGS, False))


def make_editor(tmp_path):
    p = proposal(); editor = object.__new__(NonconformingEditor)
    editor.proposals = {p['target_key']: p}; editor.binding = 'isolated-binding'
    editor.gallery = SimpleNamespace(manifest_sha256='manifest')
    editor.source_binding = lambda key: 'source-binding'
    editor.identity = lambda key: dict(target_key=key)
    editor.proposal_dependency_current = lambda key: True
    editor.store = MaskReviewStore(tmp_path/'isolated-reviews', 'formal')
    return editor, p


def payload(p, polygon=None):
    polygon = [] if polygon is None else polygon
    return dict(binding='isolated-binding', source_binding='source-binding', proposal_id=sha(p),
        expected_revision=0, reviewer='test', note='明确不合格', polygon=polygon,
        quality_decision='redrawn_pending_quality_check' if polygon else 'untraceable')


def test_no_polygon_is_fabricated_for_rejected_target():
    p = proposal(); validate_target(p)
    p['polygon'] = [[0, 0], [3, 0], [3, 3]]
    with pytest.raises(ValueError):
        validate_target(p)


@pytest.mark.parametrize('field', FALSE_FLAGS)
def test_no_eligibility_or_count_flag_can_be_promoted(field):
    p = proposal(); p[field] = True
    with pytest.raises(ValueError):
        validate_target(p)


def test_untraceable_save_is_an_event_not_a_contour(tmp_path):
    editor, p = make_editor(tmp_path); value = editor.save(p['target_key'], payload(p))
    assert value['polygon'] == [] and value['vertex_count'] == 0
    assert value['event_kind'] == 'human_nonconforming_mask_review'
    assert value['proposal_publication'] == 'nonconforming-v1'
    assert all(value[field] is False for field in FALSE_FLAGS)
    assert len(editor.store.history(p['target_key'])) == 1
    with pytest.raises(ReviewError, match='没有掩膜'):
        editor.export(p['target_key'], 'mask.png')


def test_redraw_stays_isolated_and_ineligible_even_with_malicious_request_flags(tmp_path):
    editor, p = make_editor(tmp_path); data = payload(p, [[10, 10], [60, 10], [50, 50], [10, 45]])
    data.update(dict.fromkeys(FALSE_FLAGS, True)); value = editor.save(p['target_key'], data)
    assert value['vertex_count'] == 4 and all(value[field] is False for field in FALSE_FLAGS)
    assert value['source_quality'] == 'nonconforming' and value['status'] == 'nonconforming_human_review_not_counted'
    raw, mime, name = editor.export(p['target_key'], 'labelme.json')
    assert b'"nonconforming":true' in raw and 'nonconforming' in name


def test_cas_failure_keeps_first_revision_and_no_second_event(tmp_path):
    editor, p = make_editor(tmp_path); data = payload(p); editor.save(p['target_key'], data)
    with pytest.raises(ReviewError) as error:
        editor.save(p['target_key'], data)
    assert error.value.status == 409 and len(editor.store.history(p['target_key'])) == 1


@pytest.mark.parametrize('decision,points', [('accepted', []), ('untraceable', [[1, 1], [2, 1], [1, 2]]),
    ('redrawn_pending_quality_check', [[1, 1], [2, 1]])])
def test_invalid_quality_decision_or_partial_polygon_is_not_saved(tmp_path, decision, points):
    editor, p = make_editor(tmp_path); data = payload(p, points); data['quality_decision'] = decision
    with pytest.raises(ReviewError):
        editor.save(p['target_key'], data)
    assert editor.store.summary() == {}


def test_stale_source_and_foreign_target_never_save(tmp_path):
    editor, p = make_editor(tmp_path); editor.proposal_dependency_current = lambda key: False
    with pytest.raises(ReviewError) as error:
        editor.save(p['target_key'], payload(p))
    assert error.value.status == 409 and editor.store.summary() == {}
    with pytest.raises(ReviewError) as error:
        editor.save('b'*24, payload(p))
    assert error.value.status == 404


def test_history_restore_is_an_append_not_overwrite(tmp_path):
    editor, p = make_editor(tmp_path); first = editor.save(p['target_key'], payload(p))
    data = payload(p, [[5, 5], [60, 5], [60, 40], [5, 40]]); data['expected_revision'] = 1
    editor.save(p['target_key'], data)
    restored = payload(p); restored.update(expected_revision=2, restored_from_revision=1)
    third = editor.save(p['target_key'], restored)
    assert third['revision'] == 3 and third['restored_from_revision'] == 1
    assert editor.store.history(p['target_key'])[-1] == first


def test_cannot_use_production_mask_store():
    from pallet.mask_nonconforming_review import PROJECT
    with pytest.raises(ValueError, match='isolated'):
        NonconformingEditor(None, PROJECT/'outputs/pallet_mask_gallery_reviews_v1', 'x'*32)


def test_ui_copy_has_blank_drawing_namespace_and_no_auto_record_on_next():
    text = editor_script()
    assert 'mask-nonconforming-v1:' in text and 'if(drawing)' in text
    assert 'd.polygon.length>=0' in text and 'else if(!polygon.length)' in text
    assert 'await save(offset>0' not in text and '无法描绘' in text
