from __future__ import annotations

import logging
import os
import sys
import typing

import libtbx.load_env

import dxtbx.format.Registry

from .version import version as __version__  # noqa: F401

if typing.TYPE_CHECKING:
    from dxtbx.format.Format import Format

logging.getLogger("dxtbx").addHandler(logging.NullHandler())


class IncorrectFormatError(RuntimeError):
    """
    An exception class for an incorrect format error
    """

    def __init__(self, format_instance, filename):
        super().__init__(f"Could not open {filename} as {str(format_instance)}")
        self.args = (format_instance, filename)


def load(filename: str | bytes | os.PathLike) -> Format:
    """Use DXTBX to load the input filename.

    Args:
        filename:  The input filename

    Returns
        A dxtbx Format-subclass instance for the file type

    Raises:
        IOError: If the file format could not be determined
    """
    format_instance = dxtbx.format.Registry.get_format_class_for_file(filename)
    if not format_instance:
        raise ValueError(f"Could not find matching format for {filename!r}")
    return format_instance(os.fspath(filename))
