from __future__ import annotations

from collections.abc import Iterable, Mapping
import logging
from pathlib import Path

from ..utils.record_tools import split_record
from .writer import InfluxWriter

logger = logging.getLogger(__name__)


def write_batch(
    records: Iterable[Mapping[str, object]],
    *,
    settings_path: str | Path | None = None,
    continue_on_error: bool = False,
) -> dict[str, int]:
    """Write multiple QOI records.

    Parameters
    ----------
    records : Iterable[Mapping[str, object]]
        Record dictionaries using standard keys and optional
        ``extra_tags`` / ``extra_fields``.
    settings_path : str | Path | None, default=None
        Optional path to settings TOML.
    continue_on_error : bool, default=False
        If ``True``, continue writing after per-record failures.

    Returns
    -------
    dict[str, int]
        Summary counters: ``records_total``, ``records_written``,
        and ``records_failed``.
    """
    records_total = 0
    records_written = 0
    records_failed = 0

    with InfluxWriter.from_toml(settings_path) as writer:
        for raw_record in records:
            records_total += 1
            record, extra_tags, extra_fields = split_record(raw_record)
            try:
                writer.write_record(
                    record,
                    extra_tags=extra_tags,
                    extra_fields=extra_fields,
                )
                records_written += 1
            except Exception:
                records_failed += 1
                logger.exception("Failed writing record #%d.", records_total)
                if not continue_on_error:
                    raise

    return {
        "records_total": records_total,
        "records_written": records_written,
        "records_failed": records_failed,
    }
