"""CLI interface for trade-panorama."""
import argparse
import json
import os
import sys

from . import __version__
from .scanner import scan, aggregate


# ANSI colors (with fallback)
def _color(code, text, no_color=False):
    if no_color or not sys.stdout.isatty():
        return text
    return "\033[{}m{}\033[0m".format(code, text)


def green(t, nc=False): return _color("32", t, nc)
def red(t, nc=False): return _color("31", t, nc)
def yellow(t, nc=False): return _color("33", t, nc)
def bold(t, nc=False): return _color("1", t, nc)
def dim(t, nc=False): return _color("2", t, nc)


def format_pnl(val, nc=False):
    if val > 0:
        return green("+{:.2f}%".format(val), nc)
    elif val < 0:
        return red("{:.2f}%".format(val), nc)
    return "0.00%"


def format_usd(val, nc=False):
    if val > 0:
        return green("+${:.0f}".format(val), nc)
    elif val < 0:
        return red("-${:.0f}".format(abs(val)), nc)
    return "$0"


def print_summary(summaries, agg, no_color=False):
    nc = no_color
    print()
    print(bold("=== Trade Panorama ===", nc))
    print()

    # Per-bot table
    header = "{:<18} {:>7} {:>7} {:>10} {:>6} {:>12}".format(
        "Bot", "Trades", "WR", "PnL%", "Open", "Capital")
    print(bold(header, nc))
    print("-" * 65)

    for s in summaries:
        wr_str = "{:.0f}%".format(s.win_rate * 100) if s.total_trades > 0 else "-"
        pnl_str = format_pnl(s.total_pnl_pct, nc)
        cap_str = ""
        if s.initial_capital > 0:
            cap_str = "${:.0f}".format(s.capital)
            diff = s.capital_pnl
            if diff != 0:
                cap_str += " ({})".format(format_usd(diff, nc))

        print("{:<18} {:>7} {:>7} {:>10} {:>6} {:>12}".format(
            s.name,
            s.total_trades,
            wr_str,
            pnl_str,
            len(s.open_positions),
            cap_str,
        ))

    print("-" * 65)

    # Aggregate
    agg_wr = "{:.0f}%".format(agg["win_rate"] * 100) if agg["total_trades"] > 0 else "-"
    print("{:<18} {:>7} {:>7} {:>10} {:>6}".format(
        bold("TOTAL", nc),
        agg["total_trades"],
        agg_wr,
        format_pnl(agg["total_pnl_pct"], nc),
        agg["open_positions"],
    ))

    # Open positions detail
    all_open = []
    for s in summaries:
        all_open.extend(s.open_positions)

    if all_open:
        print()
        print(bold("Open Positions ({})".format(len(all_open)), nc))
        print("{:<18} {:<10} {:>5} {:>12} {:>10} {}".format(
            "Bot", "Asset", "Dir", "Entry", "Size", "Since"))
        print("-" * 70)
        for p in all_open:
            since = p.entry_time[:10] if p.entry_time else ""
            print("{:<18} {:<10} {:>5} {:>12.2f} {:>9} {}".format(
                p.bot, p.asset, p.direction,
                p.entry_price,
                "${:.0f}".format(p.size_usd) if p.size_usd else "-",
                since,
            ))

    print()


def main():
    parser = argparse.ArgumentParser(
        prog="trade-panorama",
        description="Unified PnL dashboard across multiple trading bots",
    )
    parser.add_argument("--version", action="version",
                        version="trade-panorama " + __version__)
    parser.add_argument("--dir", "-d", default=".",
                        help="Root directory to scan for bot data (default: .)")
    parser.add_argument("--json", action="store_true",
                        help="Output as JSON")
    parser.add_argument("--no-color", action="store_true",
                        help="Disable colored output")
    parser.add_argument("--bot", "-b", action="append",
                        help="Filter by bot name (can repeat)")

    args = parser.parse_args()
    root = os.path.abspath(args.dir)

    summaries = scan(root)

    if not summaries:
        print("No trading bot data found in: {}".format(root))
        print("Looked for: {}".format(", ".join(sorted(
            __import__("trade_panorama.parsers", fromlist=["PARSERS"]).PARSERS.keys()
        ))))
        sys.exit(1)

    # Filter by bot name
    if args.bot:
        filters = [b.lower() for b in args.bot]
        summaries = [s for s in summaries if
                     any(f in s.name.lower() for f in filters)]

    agg = aggregate(summaries)

    if args.json:
        output = {
            "bots": [s.to_dict() for s in summaries],
            "aggregate": agg,
        }
        print(json.dumps(output, indent=2, ensure_ascii=False))
    else:
        print_summary(summaries, agg, no_color=args.no_color)


if __name__ == "__main__":
    main()
