#!/usr/bin/env python3
"""Show ClickHouse cache statistics for open deviation bars."""

from datetime import UTC

from opendeviationbar.clickhouse.cache import OpenDeviationBarCache


def main() -> None:
    """Display cache statistics."""
    cache = OpenDeviationBarCache()
    print("=== ClickHouse Cache Status ===")

    # Count total bars
    result = cache.client.query(
        "SELECT count() FROM opendeviationbar_cache.open_deviation_bars"
    )
    total = result.result_rows[0][0]
    print(f"Total cached bars: {total:,}")

    # Count by symbol and threshold
    query = """
        SELECT symbol, threshold_decimal_bps, count() as bars,
               min(close_time_us) as earliest_us, max(close_time_us) as latest_us
        FROM opendeviationbar_cache.open_deviation_bars
        GROUP BY symbol, threshold_decimal_bps
        ORDER BY bars DESC
    """
    result = cache.client.query(query)

    print("\nBy symbol/threshold:")
    for row in result.result_rows[:10]:
        symbol, threshold, bars, earliest_us, latest_us = row
        # Convert us to readable date
        from datetime import datetime

        earliest = datetime.fromtimestamp(earliest_us / 1_000_000, tz=UTC).strftime(
            "%Y-%m-%d"
        )
        latest = datetime.fromtimestamp(latest_us / 1_000_000, tz=UTC).strftime("%Y-%m-%d")
        print(f"  {symbol} @ {threshold} dbps: {bars:,} bars ({earliest} to {latest})")

    max_display = 10
    if len(result.result_rows) > max_display:
        print(f"  ... and {len(result.result_rows) - max_display} more")


if __name__ == "__main__":
    main()
