#!/usr/bin/env python3
"""Verify Stathera overlap/gap counts for streaming symbols.

Reusable across all spike approaches. Run on bigblack:
    ~/opendeviationbar-py/.venv/bin/python3 scripts/verify_stathera.py
"""
import sys
from opendeviationbar.clickhouse.cache import OpenDeviationBarCache


def check_stathera(symbols: list[str] | None = None) -> dict:
    """Query Stathera for overlaps and gaps on streaming symbols."""
    if symbols is None:
        symbols = ["BTCUSDT", "ETHUSDT"]

    sym_list = ", ".join(f"'{s}'" for s in symbols)
    query = f"""
    WITH bars AS (
        SELECT symbol, threshold_decimal_bps,
               first_agg_trade_id,
               lagInFrame(last_agg_trade_id, 1) OVER w AS prev_last_tid,
               first_agg_trade_id - lagInFrame(last_agg_trade_id, 1) OVER w - 1 AS tid_delta,
               toDate(close_time_ms/1000) AS bar_date
        FROM opendeviationbar_cache.open_deviation_bars FINAL
        WHERE symbol IN ({sym_list})
        WINDOW w AS (PARTITION BY symbol, threshold_decimal_bps, ouroboros_mode
                     ORDER BY first_agg_trade_id)
    )
    SELECT
        toDate(now()) AS today,
        countIf(tid_delta < 0) AS total_overlaps,
        countIf(tid_delta < 0 AND bar_date = today()) AS today_overlaps,
        countIf(tid_delta > 0 AND tid_delta < 500000) AS total_intra_gaps,
        countIf(tid_delta > 0 AND tid_delta < 500000 AND bar_date = today()) AS today_intra_gaps
    FROM bars WHERE prev_last_tid > 0
    """

    cache = OpenDeviationBarCache()
    result = cache.client.query(query)
    row = result.result_rows[0]
    return {
        "today": str(row[0]),
        "total_overlaps": row[1],
        "today_overlaps": row[2],
        "total_intra_gaps": row[3],
        "today_intra_gaps": row[4],
    }


def check_writer_versions(symbols: list[str] | None = None) -> list[dict]:
    """Show which writers produced bars for today."""
    if symbols is None:
        symbols = ["BTCUSDT", "ETHUSDT"]

    sym_list = ", ".join(f"'{s}'" for s in symbols)
    query = f"""
    SELECT opendeviationbar_version, count() AS bars,
           min(toDateTime64(open_time_ms/1000, 0)) AS earliest,
           max(toDateTime64(close_time_ms/1000, 0)) AS latest
    FROM opendeviationbar_cache.open_deviation_bars FINAL
    WHERE symbol IN ({sym_list})
      AND toDate(close_time_ms/1000) = today()
    GROUP BY opendeviationbar_version
    ORDER BY earliest
    """

    cache = OpenDeviationBarCache()
    result = cache.client.query(query)
    return [
        {
            "version": row[0],
            "bars": row[1],
            "earliest": str(row[2]),
            "latest": str(row[3]),
        }
        for row in result.result_rows
    ]


if __name__ == "__main__":
    print("=== Stathera Check (streaming symbols) ===")
    stathera = check_stathera()
    for k, v in stathera.items():
        print(f"  {k}: {v}")

    print("\n=== Writer Versions (today) ===")
    versions = check_writer_versions()
    for v in versions:
        print(f"  {v['version']}: {v['bars']} bars ({v['earliest']} → {v['latest']})")

    # Exit code: 0 if no today overlaps, 1 if overlaps exist
    if stathera["today_overlaps"] > 0:
        print(f"\nFAIL: {stathera['today_overlaps']} overlaps on today")
        sys.exit(1)
    else:
        print("\nPASS: zero overlaps on today")
        sys.exit(0)
