#!/usr/bin/env python3
"""清空中控 K 线 SQLite 缓存(hub_kline.db),便于清库后全量重拉.

用法(Linux 云服务器,在仓库根目录):
  python3 scripts/clear_hub_kline_db.py --dry-run
  python3 scripts/clear_hub_kline_db.py --apply
  python3 scripts/clear_hub_kline_db.py --apply --exchange binance --symbol BTC/USDT --timeframe 15m

默认库路径:环境变量 HUB_KLINE_DB_PATH,或 manual_trading_hub/data/hub_kline.db
"""
from __future__ import annotations

import argparse
import os
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))

from lib.hub.hub_kline_store import (  # noqa: E402
    clear_all_bars,
    clear_series_bars,
    default_db_path,
    init_db,
)


def main() -> int:
    parser = argparse.ArgumentParser(description="Clear manual-trading-hub K-line SQLite cache.")
    parser.add_argument(
        "--db",
        default=os.getenv("HUB_KLINE_DB_PATH", "").strip() or str(default_db_path()),
        help="hub_kline.db path",
    )
    parser.add_argument("--exchange", default="", help="exchange_key, e.g. binance")
    parser.add_argument("--symbol", default="", help="symbol, e.g. BTC/USDT")
    parser.add_argument("--timeframe", default="", help="optional timeframe, e.g. 15m")
    parser.add_argument("--dry-run", action="store_true", help="count only")
    parser.add_argument("--apply", action="store_true", help="execute delete")
    args = parser.parse_args()

    db_path = Path(args.db)
    if not db_path.is_file():
        print(f"DB not found: {db_path}", file=sys.stderr)
        return 1

    init_db(db_path)
    ex = (args.exchange or "").strip().lower()
    sym = (args.symbol or "").strip().upper()
    tf = (args.timeframe or "").strip().lower() or None

    if args.dry_run and not args.apply:
        import sqlite3

        conn = sqlite3.connect(str(db_path))
        try:
            if ex and sym:
                if tf:
                    n = conn.execute(
                        "SELECT COUNT(*) FROM ohlcv_bars WHERE exchange_key=? AND symbol=? AND timeframe=?",
                        (ex, sym, tf),
                    ).fetchone()[0]
                    print(f"would delete series rows: {n} ({ex} {sym} {tf})")
                else:
                    n = conn.execute(
                        "SELECT COUNT(*) FROM ohlcv_bars WHERE exchange_key=? AND symbol=?",
                        (ex, sym),
                    ).fetchone()[0]
                    print(f"would delete symbol rows: {n} ({ex} {sym} all tf)")
            else:
                n = conn.execute("SELECT COUNT(*) FROM ohlcv_bars").fetchone()[0]
                print(f"would delete all ohlcv_bars rows: {n}")
        finally:
            conn.close()
        return 0

    if not args.apply:
        print("Specify --apply to delete (or --dry-run to preview).", file=sys.stderr)
        return 1

    if ex and sym:
        removed = clear_series_bars(ex, sym, tf, db_path)
        scope = f"{ex} {sym}" + (f" {tf}" if tf else " (all timeframes)")
        print(f"cleared {removed} rows for {scope}")
    else:
        removed = clear_all_bars(db_path)
        print(f"cleared all {removed} ohlcv_bars rows from {db_path}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
