#!/usr/bin/env python3
"""Gap backfill CLI (Issue #92).

Bridges the gap between latest cache bar and now via Vision first → REST fallback.

USAGE:
======
# Single-shot: backfill one symbol
uv run python scripts/gap_backfill.py --symbol BTCUSDT --threshold 250

# Single-shot: backfill all cached pairs
uv run python scripts/gap_backfill.py --all

NOTE: The --loop daemon mode was removed in #238 Phase 2.
Use `kintsugi --daemon` instead (trailing-edge fill is now integrated).
"""

from __future__ import annotations

import argparse
import sys


def main() -> int:
    parser = argparse.ArgumentParser(
        description="Gap backfill (Vision→REST) for open deviation bar cache",
    )

    mode = parser.add_mutually_exclusive_group(required=True)
    mode.add_argument(
        "--symbol",
        help="Backfill a single symbol (requires --threshold)",
    )
    mode.add_argument(
        "--all",
        action="store_true",
        help="Backfill all cached symbol x threshold pairs",
    )

    parser.add_argument(
        "--threshold",
        type=int,
        default=250,
        help="Threshold in decimal basis points (default: 250)",
    )
    parser.add_argument(
        "--no-microstructure",
        action="store_true",
        help="Skip microstructure features (faster)",
    )
    parser.add_argument(
        "--verbose",
        action="store_true",
        help="Enable verbose logging",
    )

    args = parser.parse_args()

    from opendeviationbar.logging import setup_service_logging

    logger = setup_service_logging("gap-backfill", verbose=args.verbose)

    include_micro = not args.no_microstructure

    from opendeviationbar.backfill import (
        backfill_all_gaps,
        backfill_gap,
    )

    if args.symbol:
        result = backfill_gap(
            args.symbol,
            args.threshold,
            include_microstructure=include_micro,
            verbose=args.verbose,
        )
        if result.error:
            logger.bind(error=str(result.error)).error("Backfill error")
            return 1
        logger.bind(
            bars_written=result.bars_written,
            gap_minutes=round(result.gap_seconds / 60, 1),
        ).info("Backfill complete")
        return 0

    if args.all:
        results = backfill_all_gaps(
            include_microstructure=include_micro,
            verbose=args.verbose,
        )
        total = sum(r.bars_written for r in results)
        errors = sum(1 for r in results if r.error)
        logger.bind(
            pairs=len(results),
            bars_written=total,
            errors=errors,
        ).info("Backfill all complete")
        return 1 if errors > 0 else 0

    return 0


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