"""Scans for coins that experienced a 'pump' in the last N days, along with the dates (DRY_RUN public data, no API key required).

A day counts as a 'pump' when (intraday high / previous close - 1) OR (close / open - 1)
exceeds the threshold (--min-pump) AND that day's quote (USDT) volume is above --min-vol (a liquidity
filter that weeds out dead micro-cap wicks). For each coin, the LARGEST pump day within the 30-day window is reported.

Usage:
  python scripts/pump_history.py [--days 30] [--min-pump 30] [--min-vol 300000] [--interval 1d] [--top 60]
"""
from __future__ import annotations

import argparse
import sys

from coinbot.config import load_settings
from coinbot.exchange import Exchange


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--days", type=int, default=30)
    ap.add_argument("--min-pump", type=float, default=30.0, help="min pump %% (gün-içi zirve veya gün getirisi)")
    ap.add_argument("--min-vol", type=float, default=300_000.0, help="o günün min quote hacmi ($)")
    ap.add_argument("--interval", default="1d")
    ap.add_argument("--top", type=int, default=60)
    args = ap.parse_args()

    ex = Exchange(load_settings("config.yaml", mode_override="dry_run"))
    syms = ex.get_usdt_symbols()
    limit = args.days + 3
    print(f"{len(syms)} USDT paritesi taranıyor (son {args.days} gün, {args.interval})…", file=sys.stderr)

    results = []
    for i, sym in enumerate(syms):
        try:
            df = ex.get_klines_extended(sym, args.interval, limit)
        except Exception:  # noqa: BLE001
            continue
        if df is None or len(df) < 3:
            continue
        d = df.tail(args.days + 1)               # +1 = for the first day's previous close
        o = d["open"].to_numpy("float64")
        h = d["high"].to_numpy("float64")
        c = d["close"].to_numpy("float64")
        qv = d["quote_volume"].to_numpy("float64")
        best = None
        for j in range(1, len(d)):
            prev_close = c[j - 1]
            if prev_close <= 0 or o[j] <= 0:
                continue
            jump = (h[j] - prev_close) / prev_close * 100.0    # intraday high above previous close
            day_gain = (c[j] - o[j]) / o[j] * 100.0            # close/open daily return
            pump = max(jump, day_gain)
            if pump >= args.min_pump and qv[j] >= args.min_vol:
                if best is None or pump > best[1]:
                    best = (d.index[j], pump, qv[j], day_gain, jump, c[j])
        if best:
            results.append((sym, *best))
        if (i + 1) % 75 == 0:
            print(f"  … {i + 1}/{len(syms)}", file=sys.stderr)

    results.sort(key=lambda r: r[2], reverse=True)   # descending pump%
    last = ex.get_24h_stats()
    print(f"\n=== Son {args.days} günde ≥ %{args.min_pump:.0f} pump (o gün hacmi ≥ ${args.min_vol:,.0f}): "
          f"{len(results)} coin ===\n")
    print(f"{'COIN':<14}{'TARİH':<12}{'PUMP%':>9}{'GÜN%':>8}{'O GÜN HACMİ $':>18}{'ŞİMDİ vs O GÜN':>16}")
    for r in results[:args.top]:
        sym, dt, pump, qv, day_gain, _jump, pump_close = r
        now_px = None
        try:
            if last is not None and sym in last.index:
                now_px = float(last.loc[sym]["last_price"])
        except Exception:  # noqa: BLE001
            now_px = None
        chg = (f"{(now_px / pump_close - 1) * 100:+.0f}%" if (now_px and pump_close > 0) else "—")
        print(f"{sym:<14}{str(dt.date()):<12}{pump:>8.1f}%{day_gain:>7.1f}%{qv:>18,.0f}{chg:>16}")


if __name__ == "__main__":
    main()
