"""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).

    For gaps: checks that tid_delta == 0 at the repair point.
    For overlaps: checks that no overlap (tid_delta < 0) remains at the
    repair point. A gap (tid_delta > 0) after overlap DELETE is expected
    and will be filled on the next pass — not a verification failure.
    """
    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)

    # For gaps: anchor < resume, so range is [anchor, resume].
    # For overlaps: anchor > resume, so use wider range [resume, anchor]
    # to capture bars around the overlap point.
    lo = min(shard.anchor_last_tid, shard.resume_first_tid)
    hi = max(shard.anchor_last_tid, shard.resume_first_tid)

    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 >= {lo:Int64}
              AND first_agg_trade_id <= {hi:Int64}
            ORDER BY first_agg_trade_id, close_time_us
            """,
            parameters={
                "symbol": shard.symbol,
                "threshold": shard.threshold_decimal_bps,
                "ouroboros": ouroboros_mode,
                "lo": lo,
                "hi": hi,
            },
        )

        for row in result.result_rows:
            td = row[0]
            if td is None:
                continue
            if shard.is_overlap:
                # For overlap repairs: only fail if overlap still exists.
                # A gap after overlap DELETE is expected — kintsugi fills
                # it on the next discovery cycle.
                if td < 0:
                    logger.info(
                        "verify_repair: overlap persists for %s@%d (tid_delta=%d)",
                        shard.symbol,
                        shard.threshold_decimal_bps,
                        td,
                    )
                    return False
            elif 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
