"""Scan directories for trading bot data files and aggregate."""
import json
import os
from .model import BotSummary
from .parsers import PARSERS


def find_data_files(root_dir):
    """Walk directory tree looking for known bot data files."""
    found = {}
    for dirpath, _dirnames, filenames in os.walk(root_dir):
        for fname in filenames:
            if fname in PARSERS:
                full = os.path.join(dirpath, fname)
                # Avoid duplicates: keep deepest path
                if fname not in found or len(full) > len(found[fname]):
                    found[fname] = full
    return found


def scan(root_dir, files=None):
    """Scan for all bot data and return list of BotSummary.

    Args:
        root_dir: Root directory to search for data files
        files: Optional dict of {filename: path} to use instead of scanning
    """
    if files is None:
        files = find_data_files(root_dir)

    summaries = []
    for fname, fpath in files.items():
        parser = PARSERS.get(fname)
        if not parser:
            continue
        try:
            with open(fpath) as f:
                data = json.load(f)
            summary = parser(data)
            summaries.append(summary)
        except (json.JSONDecodeError, KeyError, TypeError) as e:
            print("WARNING: Failed to parse {}: {}".format(fpath, e))

    return summaries


def aggregate(summaries):
    """Compute cross-bot aggregate stats."""
    total_trades = sum(s.total_trades for s in summaries)
    total_wins = sum(s.wins for s in summaries)
    total_pnl_pct = sum(s.total_pnl_pct for s in summaries)
    total_open = sum(len(s.open_positions) for s in summaries)
    total_capital = sum(s.capital for s in summaries)
    total_initial = sum(s.initial_capital for s in summaries)

    return {
        "bots": len(summaries),
        "total_trades": total_trades,
        "total_wins": total_wins,
        "win_rate": total_wins / total_trades if total_trades > 0 else 0,
        "total_pnl_pct": total_pnl_pct,
        "open_positions": total_open,
        "total_capital": total_capital,
        "total_initial_capital": total_initial,
        "capital_pnl": total_capital - total_initial if total_initial > 0 else 0,
    }
