#!/usr/bin/env python3
"""history.py — Displays the closed-trade history and statistics from the DB in the terminal.

Backend is selected via DATABASE_URL (defaults to SQLite state/coinbot.db; PostgreSQL on the server).

Example:
  python scripts/history.py                 # all modes, last 30 trades
  python scripts/history.py --mode live --limit 50
"""
from __future__ import annotations

import argparse
import pathlib
import sys

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

from dotenv import load_dotenv

load_dotenv(pathlib.Path(__file__).resolve().parent.parent / ".env")

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

from coinbot.db import Database

console = Console()


def main(argv: list[str] | None = None) -> int:
    p = argparse.ArgumentParser(prog="history.py", description="İşlem geçmişi + istatistik (SQLite/PostgreSQL).")
    p.add_argument("--mode", default=None, choices=["dry_run", "testnet", "live"], help="Mod filtresi (opsiyonel).")
    p.add_argument("--limit", type=int, default=30, help="Gösterilecek işlem sayısı (varsayılan 30).")
    args = p.parse_args(argv)

    try:
        db = Database()
    except Exception as exc:  # noqa: BLE001
        console.print(f"[bold red]DB acilamadi:[/] {exc}")
        return 1

    st = db.stats(args.mode)
    pf = "∞" if st["profit_factor"] is None else st["profit_factor"]
    console.print(
        f"[bold]İstatistik[/] (mod=[cyan]{args.mode or 'hepsi'}[/]): "
        f"işlem={st['num_trades']}  kazanma=%{st['win_rate']}  "
        f"profit_factor={pf}  toplam_pnl={st['total_pnl']}"
    )

    rows = db.recent_trades(args.mode, args.limit)
    table = Table(title=f"Son {len(rows)} İşlem", show_lines=False)
    for col in ("Sembol", "Mod", "PnL", "Giriş", "Çıkış", "Sebep", "Kapanış"):
        table.add_column(col, justify="right" if col in ("PnL", "Giriş", "Çıkış") else "left")
    for r in rows:
        pnl = r.get("pnl") or 0.0
        table.add_row(
            str(r.get("symbol")), str(r.get("mode")),
            f"[green]{pnl:.2f}[/]" if pnl > 0 else (f"[red]{pnl:.2f}[/]" if pnl < 0 else f"{pnl:.2f}"),
            f"{r.get('entry_price') or 0:.4f}", f"{r.get('exit_price') or 0:.4f}",
            str(r.get("reason") or "—"), str(r.get("closed_at") or "—")[:16],
        )
    console.print(table)
    if not rows:
        console.print("[dim]Henüz kayıtlı işlem yok (bot kapanan işlem yaptıkça birikir).[/]")
    return 0


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