"""Format alias resolution and writer registry.

Writers register themselves by being imported. Callers that need a writer
should call `bootstrap()` first; the pipeline does this in one place."""

from __future__ import annotations

from aa_auto_sdr.output.protocols import Writer

_ALIASES: dict[str, list[str]] = {
    "all": ["excel", "csv", "json", "html", "markdown"],
    "reports": ["excel", "markdown"],
    "data": ["csv", "json"],
    "ci": ["json", "markdown"],
}

_CONCRETE = {"excel", "csv", "json", "html", "markdown", "excel-template", "notion"}

_WRITERS: dict[str, Writer] = {}


def resolve_formats(name: str) -> list[str]:
    """Resolve a user-facing format name to one or more concrete format keys."""
    if name in _ALIASES:
        return list(_ALIASES[name])
    if name in _CONCRETE:
        return [name]
    raise KeyError(f"Unknown format or alias: {name!r}")


def swap_excel_for_template(formats: list[str]) -> list[str]:
    """Replace every 'excel' entry with 'excel-template'; preserve order, dedupe.

    Called after format resolution when --template is set. v1.16.0.
    """
    seen: set[str] = set()
    out: list[str] = []
    for fmt in formats:
        replacement = "excel-template" if fmt == "excel" else fmt
        if replacement in seen:
            continue
        seen.add(replacement)
        out.append(replacement)
    return out


def register_writer(name: str, writer: Writer) -> None:
    _WRITERS[name] = writer


def get_writer(name: str) -> Writer:
    if name not in _WRITERS:
        raise KeyError(f"No writer registered for format {name!r}")
    return _WRITERS[name]


def bootstrap() -> None:
    """Import the v0.2 writer modules so they self-register.

    Heavy deps (pandas, xlsxwriter) are pulled in here, not at registry import,
    so the fast-path entry stays cheap."""
    from aa_auto_sdr.output.writers import csv as _csv  # noqa: F401
    from aa_auto_sdr.output.writers import excel as _excel  # noqa: F401
    from aa_auto_sdr.output.writers import excel_template as _excel_template  # noqa: F401
    from aa_auto_sdr.output.writers import html as _html  # noqa: F401
    from aa_auto_sdr.output.writers import json as _json  # noqa: F401
    from aa_auto_sdr.output.writers import markdown as _markdown  # noqa: F401
    from aa_auto_sdr.output.writers import notion as _notion  # noqa: F401
