import jsonl
import zlib
from gzip import BadGzipFile, open as gzip_open
from io import StringIO
from pathlib import Path
from typing import Any


def load_jsonl(file: Path) -> tuple[dict[str, Any], ...]:
    """
    Load JSONL data from a file (gzip compressed or plain text).

    Parameters
    ----------
    file : Path
        Path to the JSONL file (can be .jsonl or .jsonl.gz)

    Returns
    -------
    tuple[dict[str, Any], ...]
        Tuple of dictionaries parsed from the JSONL file

    Raises
    ------
    FileNotFoundError
        If the file does not exist
    IOError
        If there's an error reading the file
    ValueError
        If the file contains invalid JSONL data
    """
    if not file.exists():
        raise FileNotFoundError(f"File not found: {file}")

    if not file.is_file():
        raise ValueError(f"Path is not a file: {file}")

    def _load_jsonl(source: Any) -> tuple[dict[str, Any], ...]:
        return tuple(jsonl.load(source))

    def _read_magic(path: Path) -> bytes:
        try:
            with path.open("rb") as fh:
                return fh.read(2)
        except FileNotFoundError:
            raise
        except OSError:
            return b""

    try:
        data = _load_jsonl(file)
    except BadGzipFile:
        magic = _read_magic(file)
        looks_gzip = magic == b"\x1f\x8b"

        # If it looks like gzip, try an explicit gzip open before giving up.
        if looks_gzip:
            try:
                with gzip_open(file, "rt", encoding="utf-8") as gz:
                    data = _load_jsonl(gz)
            except (BadGzipFile, OSError):
                data = None
        else:
            data = None

        if data is None:
            # If gzip stream is broken, attempt a lenient zlib decompress to salvage content.
            try:
                raw = file.read_bytes()
                dobj = zlib.decompressobj(16 + zlib.MAX_WBITS)
                text_bytes = dobj.decompress(raw) + dobj.flush()
                text = text_bytes.decode("utf-8", errors="replace")
                data = _load_jsonl(StringIO(text))
            except Exception:
                data = None

        if data is None:
            # Fall back to plain text even if the header hinted gzip.
            try:
                with file.open("r", encoding="utf-8", errors="replace") as plain_file:
                    data = _load_jsonl(plain_file)
            except FileNotFoundError as e:
                raise FileNotFoundError(f"Error reading file {file}: {e}")
            except ValueError as e:
                raise ValueError(f"Invalid JSONL format in {file} (plain read fallback): {e}")
            except Exception as e:
                raise IOError(
                    f"Error loading JSONL file {file} without compression (magic={magic!r}): {type(e).__name__}: {e}"
                )
    except FileNotFoundError as e:
        raise FileNotFoundError(f"Error reading file {file}: {e}")
    except ValueError as e:
        raise ValueError(f"Invalid JSONL format in {file}: {e}")
    except Exception as e:
        raise IOError(f"Error loading JSONL file {file}: {type(e).__name__}: {e}")

    if not data:
        raise ValueError(f"JSONL file is empty: {file}")

    return data
