"""Remaining capacity uses real distinct saves and never reissues protections."""
import importlib.util
from pathlib import Path

import pytest

PROJECT = Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location('remaining_capacity', PROJECT/'scripts/audit_mask_under50_remaining.py')
audit = importlib.util.module_from_spec(spec); spec.loader.exec_module(audit)


def record(key, frame, cls):
    return dict(target_key=key, row=dict(frame_id=frame, final_class_id=cls))


def test_counts_saved_distinct_images_not_machine_coverage():
    records = [record(str(c)+'-'+str(i), str(c)+'-'+str(i), c) for c in range(1, 23)
        for i in range(43 if c == 19 else 50)]
    counts, gaps = audit.remaining_gaps(records)
    assert counts[11] == counts[12] == counts[16] == counts[17] == counts[20] == 50
    assert gaps == {19: 7}


@pytest.mark.parametrize('rows', [[record('same', 'a', 19), record('same', 'b', 19)],
    [record('a', 'same', 19), record('b', 'same', 19)]])
def test_duplicate_target_or_frame_cannot_inflate_saved_count(rows):
    with pytest.raises(ValueError, match='distinct'):
        audit.remaining_gaps(rows)


@pytest.mark.parametrize('protected,frames,expected', [({'key'}, set(), 'protected_target'),
    (set(), {'frame'}, 'protected_frame')])
def test_protection_precedes_quality_or_image_read(monkeypatch, protected, frames, expected):
    def forbidden(*args):
        raise AssertionError('Must not reopen protected targets')
    monkeypatch.setattr(audit, 'native_quality', forbidden)
    assert audit.classify({'frame_id': 'frame'}, 'key', protected, frames, set(), None, forbidden) == (expected, None)


def test_existing_native_size_gate_remains_enforced():
    row = dict(frame_id='frame', size=[224, 172], bbox=dict(x=44.46, y=110.04, width=16.3, height=32.18))
    status, quality = audit.classify(row, 'key', set(), set(), set(), None, lambda row: 'unused')
    assert status == 'bbox_too_small_for_manual_tracing' and quality is None


def test_protected_image_bytes_are_not_a_new_candidate(monkeypatch):
    monkeypatch.setattr(audit, 'native_quality', lambda *args: ({'clarity_score': 1}, None))
    status, _ = audit.classify({'frame_id': 'frame'}, 'key', set(), set(), {'same-bytes'}, None, lambda row: 'same-bytes')
    assert status == 'duplicate_protected_native_image_bytes'


def test_preflight_candidate_is_not_called_visual_approval(monkeypatch):
    monkeypatch.setattr(audit, 'native_quality', lambda *args: ({'clarity_score': 1}, None))
    status, _ = audit.classify({'frame_id': 'frame'}, 'key', set(), set(), set(), None, lambda row: 'new')
    assert status == 'new_native_quality_candidate_pending_visual_inspection'


def test_never_overwrites_existing_audit_output(tmp_path):
    with pytest.raises(ValueError, match='Fresh audit'):
        audit.audit(tmp_path/'snapshot', tmp_path/'pack', tmp_path)
