"""Formatters for dlist output

Formatters convert Dlist objects into various external formats.

Available formatters::

    'json'   – JSONFormatter      – JSON arrays / objects
    'ascii'  – ASCIIFormatter     – box-drawing tables (terminal)
    'md'     – MarkdownFormatter  – pipe-delimited Markdown tables
    'latex'  – LaTeXFormatter     – LaTeX tabular environments
    'excel'  – ExcelFormatter     – .xlsx workbooks (requires openpyxl)

Usage::

    from dlist.formatters import get_formatter

    fmt = get_formatter('ascii')
    print(fmt.format(my_dlist, keys=['name', 'age'], width='auto'))

    # Categorized output
    print(fmt.format_categorized(my_dlist, ['type'], ['name', 'age'],
          titles={'type': 'Type: {}', 'name': 'Name', 'age': 'Age'}))

    # Save to file
    fmt.save(my_dlist, 'output.txt', keys=['name', 'age'])

Custom formatters can be registered with ``register_formatter()``.
"""

from .json_formatter import JSONFormatter
from .ascii_formatter import ASCIIFormatter
from .md_formatter import MarkdownFormatter
from .latex_formatter import LaTeXFormatter

_FORMATTERS = {
    'json': JSONFormatter(),
    'ascii': ASCIIFormatter(),
    'md': MarkdownFormatter(),
    'latex': LaTeXFormatter(),
    'excel': None,  # lazy — loaded on first use
}


def get_formatter(format_type):
    """Get formatter by type

    Parameters:
        format_type (str): Type of formatter ('json', 'ascii', 'md', 'latex', 'excel')

    Returns:
        BaseFormatter: Formatter instance

    Raises:
        ValueError: If format_type is unknown
        ImportError: If the formatter requires an uninstalled dependency
    """
    key = format_type.lower()
    if key not in _FORMATTERS:
        raise ValueError(f"Unknown format: {format_type}. Available: {list(_FORMATTERS.keys())}")
    if _FORMATTERS[key] is None:
        # Lazy import
        if key == 'excel':
            from .excel_formatter import ExcelFormatter
            _FORMATTERS['excel'] = ExcelFormatter()
    return _FORMATTERS[key]


def register_formatter(name, formatter):
    """Register a custom formatter

    Parameters:
        name (str): Name to register formatter under
        formatter (BaseFormatter): Formatter instance
    """
    _FORMATTERS[name.lower()] = formatter


__all__ = [
    'JSONFormatter',
    'ASCIIFormatter',
    'MarkdownFormatter',
    'LaTeXFormatter',
    'ExcelFormatter',
    'get_formatter',
    'register_formatter',
]
