#!/usr/bin/env python3
"""robustness.py — tests the strategy across MULTIPLE PERIODS and reports consistency (profit evidence).

Distinguishes whether the edge measured in a single window is luck or solid: it splits the
history into N consecutive windows, runs a backtest in each, and produces an "is it robust?" verdict.
Used as a GATE for the transition to LIVE (does NOT send real orders).

Example:
  python scripts/robustness.py --symbols BTCUSDT,ETHUSDT --windows 3 --bars 500
  python scripts/robustness.py --top 5 --windows 4 --bars 400   # first 5 from the universe
"""
from __future__ import annotations

import argparse
import pathlib
import sys

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent))

from rich.console import Console
from rich.table import Table

from coinbot.backtest import run_robustness
from coinbot.config import load_settings
from coinbot.exchange import Exchange, ExchangeError
from coinbot.screener import screen_universe

console = Console()


def main(argv: list[str] | None = None) -> int:
    p = argparse.ArgumentParser(prog="robustness.py", description="Çok-dönem robustness backtest")
    p.add_argument("--config", default="config.yaml")
    p.add_argument("--mode", default="dry_run", choices=["dry_run", "testnet", "live"])
    p.add_argument("--symbols", default=None, help="virgülle ayrık; yoksa evrenden ilk --top")
    p.add_argument("--windows", type=int, default=3)
    p.add_argument("--bars", type=int, default=500, help="pencere başına bar sayısı")
    p.add_argument("--top", type=int, default=5, help="--symbols yoksa evrenden kaç sembol")
    args = p.parse_args(argv)

    settings = load_settings(args.config, mode_override=args.mode)
    ex = Exchange(settings)

    if args.symbols:
        symbols = [s.strip().upper() for s in args.symbols.split(",") if s.strip()]
    else:
        try:
            symbols = screen_universe(ex, settings)[: args.top]
        except ExchangeError as e:
            console.print(f"[red]Evren taranamadı: {e}[/]")
            return 2
    if not symbols:
        console.print("[red]Sembol yok.[/]")
        return 2

    console.print(
        f"[cyan]Robustness[/]: {symbols} · {args.windows} pencere × {args.bars} bar · "
        f"strateji tipi=[b]{settings.strategy.strategy_type}[/] · skor>={settings.strategy.score_threshold}"
    )
    r = run_robustness(ex, symbols, settings, windows=args.windows, bars_per_window=args.bars)

    t = Table(title="Pencere Bazında Sonuçlar")
    for c in ("#", "Başlangıç", "Bitiş", "Getiri %", "İşlem", "PF", "Maks DD %", "Kazanma %"):
        t.add_column(c, justify="right")
    for w in r["per_window"]:
        pf = w["profit_factor"]
        pf_s = "∞" if pf is None else f"{pf}"
        t.add_row(str(w["window"]), str(w["start"])[:10], str(w["end"])[:10],
                  f"{w['return_pct']}", str(w["num_trades"]), pf_s,
                  f"{w['max_drawdown_pct']}", f"{w['win_rate']}")
    console.print(t)

    color = "green" if r["robust"] else "red"
    console.print(
        f"Kârlı pencere: [b]{r['profitable_windows']}/{r['windows']}[/] · "
        f"Ort PF: [b]{r['mean_profit_factor']}[/] · Ort getiri: [b]{r['mean_return_pct']}%[/] · "
        f"En kötü DD: [b]{r['worst_drawdown_pct']}%[/] · Toplam işlem: [b]{r['total_trades']}[/]"
    )
    console.print(f"[{color}]VERDİCT: {r['verdict']}[/]")
    console.print(
        "[dim]Not: 'ROBUST' tek başına LIVE garantisi değil — ayrıca haftalarca forward "
        "(dry_run/testnet) gözlem + maliyet sonrası pozitif edge gerekir.[/]"
    )
    return 0 if r["robust"] else 1


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