"""Post-repair verification via Stathera trade-ID continuity check."""

from __future__ import annotations

import logging

from ._helpers import _get_worker_cache
from .discovery import Shard

logger = logging.getLogger(__name__)


def verify_repair(shard: Shard) -> bool:
    """Verify a Stathera anomaly has been healed via direct ClickHouse query (Issue #158).

    Checks whether any trade-ID discontinuity (gap or overlap) between
    anchor_last_tid and resume_first_tid still exists. Returns True if
    all bars in the range have tid_delta == 0.
    """
    if shard.anchor_last_tid is None or shard.resume_first_tid is None:
        # Genesis shards intentionally have no anchor — expected, not a warning.
        log = logger.debug if shard.is_genesis else logger.warning
        log(
            "verify_repair: no trade-ID anchors for %s@%d — skipping",
            shard.symbol,
            shard.threshold_decimal_bps,
        )
        return True  # Can't verify without anchors, assume healed

    from ._helpers import _get_mode_for_symbol

    ouroboros_mode = _get_mode_for_symbol(shard.symbol)

    try:
        cache = _get_worker_cache()
        result = cache.client.query(
            """
            SELECT
                first_agg_trade_id - lagInFrame(last_agg_trade_id, 1)
                    OVER (ORDER BY first_agg_trade_id, close_time_us) - 1
                    AS tid_delta
            FROM opendeviationbar_cache.open_deviation_bars FINAL
            WHERE symbol = {symbol:String}
              AND threshold_decimal_bps = {threshold:UInt32}
              AND ouroboros_mode = {ouroboros:String}
              AND first_agg_trade_id > 0
              AND last_agg_trade_id > 0
              AND last_agg_trade_id >= {anchor:Int64}
              AND first_agg_trade_id <= {resume:Int64}
            ORDER BY first_agg_trade_id, close_time_us
            """,
            parameters={
                "symbol": shard.symbol,
                "threshold": shard.threshold_decimal_bps,
                "ouroboros": ouroboros_mode,
                "anchor": shard.anchor_last_tid,
                "resume": shard.resume_first_tid,
            },
        )

        # Check if any row has tid_delta != 0 (gap or overlap still present)
        for row in result.result_rows:
            td = row[0]
            if td is not None and td != 0:
                anomaly_type = "gap" if td > 0 else "overlap"
                logger.info(
                    "verify_repair: %s persists for %s@%d (tid_delta=%d)",
                    anomaly_type,
                    shard.symbol,
                    shard.threshold_decimal_bps,
                    td,
                )
                return False

    except Exception:
        logger.exception(
            "verify_repair: ClickHouse query failed for %s@%d",
            shard.symbol,
            shard.threshold_decimal_bps,
        )
        return False

    return True
