"""Dead-letter Parquet file replay for sidecar flush failures."""

from __future__ import annotations

import logging

from ._helpers import _get_mode_for_symbol, _kintsugi_cfg

logger = logging.getLogger(__name__)


def replay_dead_letters() -> int:
    """Replay any dead-letter Parquet files from sidecar flush failures.

    Returns number of bars successfully replayed.
    """
    from opendeviationbar.sidecar import _DEAD_LETTER_DIR

    if not _DEAD_LETTER_DIR.exists():
        return 0

    import polars as pl

    from opendeviationbar.clickhouse import OpenDeviationBarCache

    total_replayed = 0
    for path in sorted(_DEAD_LETTER_DIR.glob("*.parquet")):
        parts = path.stem.split("_")
        if len(parts) < _kintsugi_cfg().min_dead_letter_parts:
            logger.warning("skipping malformed dead-letter: %s", path)
            continue

        symbol = parts[0]
        threshold = int(parts[1])
        mode = _get_mode_for_symbol(symbol)

        try:
            bars_df = pl.read_parquet(path)
            # Issue #158: Stathera source tagging
            from opendeviationbar import __version__

            source_version = f"{__version__}+kintsugi"
            with OpenDeviationBarCache() as cache:
                written = cache.store_bars_batch(
                    symbol=symbol,
                    threshold_decimal_bps=threshold,
                    bars=bars_df,
                    version=source_version,
                    ouroboros_mode=mode,
                    overlap_strategy="replace",  # Issue #158: kintsugi is authoritative
                )
            total_replayed += written
            path.unlink()
            logger.info(
                "replayed dead-letter %s: %d bars",
                path.name,
                written,
            )
        except ValueError as e:
            # (#264) Pre-write gate filters cross-midnight bars.  With
            # the filter-not-raise change, this path only fires for
            # dead letters where ALL bars are cross-midnight (batch
            # reduced to 0 rows, store returns 0).  Delete the file —
            # the trades will be re-fetched by kintsugi with proper
            # day-boundary splitting.
            logger.warning(
                "dead-letter %s permanently unplayable (day-mode gate), removing: %s",
                path.name,
                e,
            )
            path.unlink(missing_ok=True)
        except (OSError, RuntimeError, ConnectionError) as e:
            logger.warning("failed to replay dead-letter %s: %s", path, e)
            break  # Stop on first failure (ClickHouse likely down)

    if total_replayed > 0:
        logger.info("dead-letter replay: %d bars total", total_replayed)

    return total_replayed
