"""Small supplement scope, isolated service binding and unchanged old workflow."""
import importlib.util
import json
from pathlib import Path

import pytest

PROJECT = Path(__file__).resolve().parents[1]


def module(name, filename):
    spec = importlib.util.spec_from_file_location(name, PROJECT/'scripts'/filename)
    value = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(value)
    return value


builder = module('under50_builder_test', 'build_mask_under50_requests.py')
service = module('under50_service_test', 'serve_mask_under50_review.py')


def test_small_batch_uses_real_saved_shortfall_classes():
    assert builder.CLASSES == (11, 12, 16, 17, 19, 20)
    assert builder.OUT != builder.PARENT and builder.QUALITY != builder.OUT


def test_inspection_never_overwrites_previous_shortlist(tmp_path, monkeypatch):
    monkeypatch.setattr(builder, 'OUT', tmp_path)
    with pytest.raises(ValueError, match='fresh'):
        builder.review()


def test_runtime_config_is_not_active_global_config():
    assert service.CONFIG.is_relative_to(PROJECT/'outputs')
    assert not service.CONFIG.is_relative_to(PROJECT/'configs')
    assert service.PORT not in (3389, 3393)


def test_server_needs_a_matching_independent_seal(tmp_path, monkeypatch):
    monkeypatch.setattr(service, 'TASKS', tmp_path)
    (tmp_path/'manifest.json').write_text('{}')
    (tmp_path/'verification.json').write_text('{"state":"failed"}')
    with pytest.raises(ValueError, match='Independent'):
        service.configure()


def test_runtime_binding_is_exclusive_and_does_not_replace_config(tmp_path, monkeypatch):
    project = tmp_path; tasks = project/'outputs/tasks'; state = project/'outputs/runtime'
    tasks.mkdir(parents=True)
    manifest = dict(request_count=2, classes=[11, 12])
    (tasks/'manifest.json').write_text(json.dumps(manifest))
    proof = dict(state='passed', preannotations_verified=True, manifest_sha256=service.digest(tasks/'manifest.json'))
    for name in ('verification.json', 'independent_verification.json'):
        (tasks/name).write_text(json.dumps(proof))
    monkeypatch.setattr(service, 'PROJECT', project); monkeypatch.setattr(service, 'TASKS', tasks)
    monkeypatch.setattr(service, 'STATE', state); monkeypatch.setattr(service, 'CONFIG', state/'requests_config.json')
    config = service.configure(); assert config['target_per_class'] == 50
    assert config['counts_as_completed_annotation'] is False
    assert service.configure() == config
    (service.CONFIG).write_text('{"user_change":true}')
    with pytest.raises(ValueError, match='replace'):
        service.configure()
    assert json.loads(service.CONFIG.read_text()) == {'user_change': True}
