import pytest

from amunpy.amun import Amun
from amunpy.exceptions import (
    AmunPyError,
    AmunPyAttributeError,
    AmunPyChunkError,
    AmunPyVariableError,
    AmunPyDatasetError,
)


class FakeAmun(Amun):
    """Minimal fake subclass for testing base-class validation only."""

    def __init__(self):
        self.path = "fake"
        self.dataformat = None
        self.attributes = {}
        self.chunks = {}
        self.variables = {}
        self.initialized = False

    def __read_binary_data__(self, *args, **kwargs):
        raise RuntimeError("Not needed for this test")


def test_missing_mandatory_attribute():
    a = FakeAmun()
    a.attributes = {"isnap": 0}
    with pytest.raises(AmunPyAttributeError):
        a.__check_attributes__()


def test_missing_chunk_field():
    a = FakeAmun()
    a.attributes = {
        "isnap": 0,
        "nchunks": 1,
        "ndims": 2,
        "maxlev": 1,
        "nleafs": 1,
        "ncells": 8,
        "nghosts": 2,
        "xmin": 0.0,
        "xmax": 1.0,
        "ymin": 0.0,
        "ymax": 1.0,
        "xblocks": 1,
        "yblocks": 1,
    }
    a.chunks = {0: {"dblocks": 1}}
    with pytest.raises(AmunPyChunkError):
        a.__check_chunks__()


def test_no_variables_defined():
    a = FakeAmun()
    a.variables = {}
    with pytest.raises(AmunPyVariableError):
        a.__check_variables__()


def test_dataset_called_before_initialization():
    a = FakeAmun()
    with pytest.raises(AmunPyError):
        a.dataset("density")
