"""
Test module for the mbsystem module.

Authors: Sebastián Rodríguez-Martínez
Contact: srodriguez@mbari.org
"""

import os

import pytest

from navlib import mbs_read_fnv
from navlib.mbsystem import mbs_read_fnv as mbs_read_fnv_relative

# Path to resources directory
RESOURCES = os.path.join(os.path.dirname(__file__), "resources")


def test_imports():
    # Checks that the absolute and relative imports work correctly
    assert mbs_read_fnv_relative.__code__.co_code == mbs_read_fnv.__code__.co_code


def test_single_processed_file():
    file = os.path.join(RESOURCES, "00p.mb89.fnv")
    nav = mbs_read_fnv(file, processed_files=True)
    assert hasattr(nav, "utime")
    assert hasattr(nav, "longitude")
    assert hasattr(nav, "latitude")
    assert nav.utime.shape == nav.longitude.shape == nav.latitude.shape


def test_multiple_processed_files():
    files = [
        os.path.join(RESOURCES, "00p.mb89.fnv"),
        os.path.join(RESOURCES, "01p.mb89.fnv"),
    ]
    nav = mbs_read_fnv(files, processed_files=True)
    assert hasattr(nav, "utime")
    assert nav.utime.shape[0] > 0


def test_single_raw_file():
    file = os.path.join(RESOURCES, "00.mb89.fnv")
    nav = mbs_read_fnv(file, processed_files=False)
    assert hasattr(nav, "utime")
    assert hasattr(nav, "longitude")
    assert nav.utime.shape == nav.longitude.shape


def test_multiple_raw_files():
    files = [
        os.path.join(RESOURCES, "00.mb89.fnv"),
        os.path.join(RESOURCES, "01.mb89.fnv"),
    ]
    nav = mbs_read_fnv(files, processed_files=False)
    assert hasattr(nav, "utime")
    assert nav.utime.shape[0] > 0


def test_file_not_found():
    with pytest.raises(FileNotFoundError):
        mbs_read_fnv(
            os.path.join(RESOURCES, "notfoundp.mb89.fnv"), processed_files=True
        )


def test_wrong_suffix():
    file = os.path.join(RESOURCES, "00.mb89.fnv")
    with pytest.raises(ValueError):
        mbs_read_fnv(file, processed_files=True)  # processed=True expects p.mb89.fnv


def test_invalid_files_type():
    with pytest.raises(TypeError):
        mbs_read_fnv(123, processed_files=True)


def test_invalid_files_list_element_type():
    with pytest.raises(TypeError):
        mbs_read_fnv(
            [os.path.join(RESOURCES, "00p.mb89.fnv"), 123], processed_files=True
        )


def test_invalid_processed_files_type():
    file = os.path.join(RESOURCES, "00p.mb89.fnv")
    with pytest.raises(TypeError):
        mbs_read_fnv(file, processed_files="yes")


def test_empty_file(tmp_path):
    # Create an empty file with correct suffix
    empty_file = tmp_path / "empty.p.mb89.fnv"
    empty_file.write_text("")
    # Should warn and raise ValueError (no valid data)
    with pytest.warns(UserWarning):
        with pytest.raises(ValueError):
            mbs_read_fnv(str(empty_file), processed_files=True)
