#!/usr/bin/env python3
"""POC Spike A: Skip streaming symbols in kintsugi trailing-edge fill.

This script patches _trailing_edge_fill to filter out streaming symbols,
runs one trailing-edge fill pass, and verifies no new overlaps were created.

Run on bigblack:
    ~/opendeviationbar-py/.venv/bin/python3 \
        .claude/skills/streaming-writer-exclusion-spike/scripts/poc_spike_a.py

Expected: zero new +backfill bars for BTCUSDT/ETHUSDT after the pass.
"""
import json
import os
import sys
import time

# Add project to path
sys.path.insert(0, os.path.expanduser("~/opendeviationbar-py/python"))


def get_streaming_symbols() -> set[str]:
    """Get streaming symbols from env var (same as sidecar uses)."""
    raw = os.environ.get("OPENDEVIATIONBAR_STREAMING_SYMBOLS", "BTCUSDT,ETHUSDT")
    return {s.strip() for s in raw.split(",") if s.strip()}


def count_backfill_bars_for_streaming() -> int:
    """Count +backfill bars written for streaming symbols today."""
    from opendeviationbar.clickhouse.cache import OpenDeviationBarCache

    cache = OpenDeviationBarCache()
    result = cache.client.command(
        "SELECT count() FROM opendeviationbar_cache.open_deviation_bars FINAL "
        "WHERE symbol IN ('BTCUSDT', 'ETHUSDT') "
        "AND toDate(close_time_ms/1000) = today() "
        "AND opendeviationbar_version LIKE '%backfill%'"
    )
    return int(result)


def patched_trailing_edge_fill(*, include_microstructure: bool = True) -> int:
    """Trailing-edge fill that SKIPS streaming symbols.

    This is the proposed Spike A fix — identical to _trailing_edge_fill()
    but filters out symbols owned by the sidecar.
    """
    from opendeviationbar.backfill import backfill_all_gaps

    streaming = get_streaming_symbols()
    print(f"Streaming symbols to SKIP: {streaming}")

    # Get all pairs, then filter
    from opendeviationbar.backfill import _get_cached_symbol_threshold_pairs
    from opendeviationbar.symbol_registry import filter_pairs_by_registry

    all_pairs = _get_cached_symbol_threshold_pairs()
    all_pairs = filter_pairs_by_registry(all_pairs)

    # Filter OUT streaming symbols
    filtered = [(s, t) for s, t in all_pairs if s not in streaming]
    skipped = [(s, t) for s, t in all_pairs if s in streaming]

    print(f"Total pairs: {len(all_pairs)}")
    print(f"Filtered (will backfill): {len(filtered)}")
    print(f"Skipped (streaming): {len(skipped)}")

    if skipped:
        print(f"  Skipped symbols: {sorted(set(s for s, _ in skipped))}")

    # Run backfill only for non-streaming pairs
    from opendeviationbar.backfill import backfill_gap

    total_bars = 0
    for sym, thr in filtered[:3]:  # Limit to 3 pairs for POC speed
        try:
            result = backfill_gap(sym, thr, include_microstructure=include_microstructure)
            if result.bars_written > 0:
                print(f"  {sym}@{thr}: {result.bars_written} bars")
                total_bars += result.bars_written
        except Exception as e:
            print(f"  {sym}@{thr}: FAILED ({e})")

    return total_bars


def main():
    print("=" * 60)
    print("POC Spike A: Skip streaming symbols in trailing-edge fill")
    print("=" * 60)

    # Step 1: Baseline — count existing +backfill bars for streaming symbols
    before = count_backfill_bars_for_streaming()
    print(f"\nBefore: {before} +backfill bars for streaming symbols today")

    # Step 2: Run the patched trailing-edge fill
    print("\nRunning patched trailing-edge fill (streaming symbols excluded)...")
    t0 = time.monotonic()
    bars = patched_trailing_edge_fill()
    elapsed = time.monotonic() - t0
    print(f"Patched fill wrote {bars} bars in {elapsed:.1f}s (non-streaming only)")

    # Step 3: Verify — no NEW +backfill bars for streaming symbols
    after = count_backfill_bars_for_streaming()
    new_backfill = after - before
    print(f"\nAfter: {after} +backfill bars for streaming symbols today")
    print(f"New +backfill bars for streaming: {new_backfill}")

    # Step 4: Verdict
    print("\n" + "=" * 60)
    if new_backfill == 0:
        print("PASS: Zero new +backfill bars for streaming symbols")
        print("Spike A is viable — streaming exclusion works")
        return 0
    else:
        print(f"FAIL: {new_backfill} new +backfill bars for streaming symbols")
        print("Spike A did NOT prevent backfill writes — investigate")
        return 1


if __name__ == "__main__":
    sys.exit(main())
