"""Consolidated round scope, non-destructive staging and separate runtime."""
import importlib.util
from pathlib import Path

import pytest

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


def load(name):
    spec = importlib.util.spec_from_file_location(name+'_sixth_scope_test', PROJECT/'scripts'/(name+'.py'))
    module = importlib.util.module_from_spec(spec); spec.loader.exec_module(module)
    return module


def test_remaining_gap_batch_has_no_two_or_three_item_cap():
    module = load('build_mask_under50_requests_v6')
    assert module.CLASSES == (11, 12, 16, 19)
    assert module.STAGE_BUDGET == {11: 29, 12: 45, 16: 18, 19: 7}
    assert module.OUT.name == 'pallet_mask_under50_requests_v6'
    assert module.SOURCES.name == 'pallet_mask_continuation_sources_v10'


def test_stage_cannot_replace_existing_package(tmp_path, monkeypatch):
    module = load('build_mask_under50_requests_v6'); monkeypatch.setattr(module, 'OUT', tmp_path)
    with pytest.raises(ValueError, match='Fresh immutable'):
        module.review()


def test_no_post_build_extension_or_rebuild(tmp_path, monkeypatch):
    module = load('build_mask_under50_requests_v6'); monkeypatch.setattr(module, 'OUT', tmp_path)
    (tmp_path/'manifest.json').write_text('{}')
    with pytest.raises(ValueError, match='Cannot extend'):
        module.extend_class(16)
    with pytest.raises(ValueError, match='Never overwrite'):
        module.build(tmp_path/'missing.json')


def test_consolidated_service_is_separate_and_config_stays_local():
    module = load('serve_mask_under50_review_v6')
    fields = ('__file__', 'TASKS', 'STATE', 'CONFIG', 'PORT', 'LOCAL')
    old = {name: getattr(module.service, name) for name in fields}
    try:
        module.setup()
        assert module.service.PORT == 3400
        assert module.service.TASKS.name == 'pallet_mask_under50_requests_v6'
        assert module.service.CONFIG.parent.name == 'pallet_mask_under50_managed_v6'
        assert not module.service.CONFIG.is_relative_to(PROJECT/'configs')
    finally:
        for name, value in old.items():
            setattr(module.service, name, value)
