#!/usr/bin/env python3
"""
Trade Journal Analyzer - KruegerAlgorithms
https://kruegeralgorithms.com

Analyzes trade history from CSV exports (MT5, cTrader) and generates
an HTML report with performance statistics and charts.

Usage:
    python trade_journal_analyzer.py trades.csv
    python trade_journal_analyzer.py trades.csv --output report.html
    python trade_journal_analyzer.py trades.csv --risk-per-trade 1.0
"""

import argparse
import csv
import os
import sys
from datetime import datetime, timedelta
from collections import defaultdict
from typing import List, Dict, Optional

try:
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    import matplotlib.dates as mdates
    HAS_MATPLOTLIB = True
except ImportError:
    HAS_MATPLOTLIB = False
    print("Warning: matplotlib not installed. Charts will be skipped.")
    print("Install with: pip install matplotlib")


# ─── DATA STRUCTURES ───────────────────────────────────────────

class Trade:
    def __init__(self, ticket: str, symbol: str, trade_type: str,
                 open_time: datetime, close_time: datetime,
                 open_price: float, close_price: float,
                 volume: float, profit: float, commission: float = 0,
                 swap: float = 0, comment: str = ""):
        self.ticket = ticket
        self.symbol = symbol
        self.type = trade_type.upper()
        self.open_time = open_time
        self.close_time = close_time
        self.open_price = open_price
        self.close_price = close_price
        self.volume = volume
        self.profit = profit
        self.commission = commission
        self.swap = swap
        self.comment = comment
        self.net_profit = profit + commission + swap

    @property
    def is_winner(self) -> bool:
        return self.net_profit > 0

    @property
    def duration(self) -> timedelta:
        return self.close_time - self.open_time

    @property
    def weekday(self) -> str:
        return self.close_time.strftime("%A")


# ─── CSV PARSING ───────────────────────────────────────────────

def parse_datetime(s: str) -> datetime:
    """Try multiple datetime formats."""
    formats = [
        "%Y.%m.%d %H:%M:%S",  # MT5
        "%Y-%m-%d %H:%M:%S",  # Standard
        "%Y.%m.%d %H:%M",     # MT5 short
        "%d/%m/%Y %H:%M:%S",  # EU format
        "%m/%d/%Y %H:%M:%S",  # US format
    ]
    for fmt in formats:
        try:
            return datetime.strptime(s.strip(), fmt)
        except ValueError:
            continue
    raise ValueError(f"Cannot parse date: {s}")


def load_trades(filepath: str) -> List[Trade]:
    """Load trades from CSV file. Auto-detects MT5 and cTrader formats."""
    trades = []

    with open(filepath, 'r', encoding='utf-8-sig') as f:
        reader = csv.DictReader(f, delimiter='\t')

        # Detect delimiter
        f.seek(0)
        first_line = f.readline()
        f.seek(0)

        if '\t' in first_line:
            reader = csv.DictReader(f, delimiter='\t')
        elif ';' in first_line:
            reader = csv.DictReader(f, delimiter=';')
        else:
            reader = csv.DictReader(f, delimiter=',')

        headers = reader.fieldnames
        if not headers:
            raise ValueError("Empty CSV file")

        # Normalize headers
        headers_lower = [h.strip().lower() for h in headers]

        for row in reader:
            try:
                # Normalize keys
                r = {k.strip().lower(): v.strip() for k, v in row.items() if k}

                ticket = r.get('ticket', r.get('order', r.get('id', '')))
                symbol = r.get('symbol', r.get('instrument', ''))
                trade_type = r.get('type', r.get('direction', ''))

                # Skip non-trade rows
                if trade_type.lower() not in ('buy', 'sell', 'long', 'short'):
                    continue

                open_time = parse_datetime(r.get('open time', r.get('opening time', r.get('entry time', ''))))
                close_time = parse_datetime(r.get('close time', r.get('closing time', r.get('exit time', ''))))

                open_price = float(r.get('open price', r.get('entry price', r.get('opening', '0'))).replace(',', '.'))
                close_price = float(r.get('close price', r.get('exit price', r.get('closing', '0'))).replace(',', '.'))

                volume = float(r.get('volume', r.get('lots', r.get('quantity', '0'))).replace(',', '.'))
                profit = float(r.get('profit', r.get('net profit', r.get('p/l', '0'))).replace(',', '.'))

                commission = float(r.get('commission', r.get('comm', '0')).replace(',', '.') or '0')
                swap = float(r.get('swap', '0').replace(',', '.') or '0')
                comment = r.get('comment', r.get('notes', ''))

                trades.append(Trade(ticket, symbol, trade_type, open_time, close_time,
                                    open_price, close_price, volume, profit, commission, swap, comment))

            except (ValueError, KeyError) as e:
                continue  # Skip malformed rows

    return sorted(trades, key=lambda t: t.close_time)


# ─── STATISTICS ────────────────────────────────────────────────

def calculate_stats(trades: List[Trade], initial_balance: float = 10000) -> Dict:
    """Calculate comprehensive trading statistics."""
    if not trades:
        return {}

    winners = [t for t in trades if t.is_winner]
    losers = [t for t in trades if not t.is_winner]

    gross_profit = sum(t.net_profit for t in winners)
    gross_loss = abs(sum(t.net_profit for t in losers))
    net_profit = sum(t.net_profit for t in trades)

    # Equity curve + drawdown
    equity = [initial_balance]
    for t in trades:
        equity.append(equity[-1] + t.net_profit)

    peak = initial_balance
    max_dd = 0
    max_dd_pct = 0
    for eq in equity:
        if eq > peak:
            peak = eq
        dd = peak - eq
        dd_pct = dd / peak * 100 if peak > 0 else 0
        if dd > max_dd:
            max_dd = dd
            max_dd_pct = dd_pct

    # Performance by weekday
    weekday_pnl = defaultdict(list)
    for t in trades:
        weekday_pnl[t.weekday].append(t.net_profit)

    weekday_stats = {}
    for day, pnls in weekday_pnl.items():
        weekday_stats[day] = {
            'trades': len(pnls),
            'net': sum(pnls),
            'avg': sum(pnls) / len(pnls),
            'win_rate': sum(1 for p in pnls if p > 0) / len(pnls) * 100
        }

    # Performance by symbol
    symbol_pnl = defaultdict(list)
    for t in trades:
        symbol_pnl[t.symbol].append(t.net_profit)

    symbol_stats = {}
    for sym, pnls in symbol_pnl.items():
        symbol_stats[sym] = {
            'trades': len(pnls),
            'net': sum(pnls),
            'avg': sum(pnls) / len(pnls),
            'win_rate': sum(1 for p in pnls if p > 0) / len(pnls) * 100
        }

    # Streaks
    max_win_streak = max_lose_streak = 0
    current_streak = 0
    for t in trades:
        if t.is_winner:
            current_streak = current_streak + 1 if current_streak > 0 else 1
            max_win_streak = max(max_win_streak, current_streak)
        else:
            current_streak = current_streak - 1 if current_streak < 0 else -1
            max_lose_streak = max(max_lose_streak, abs(current_streak))

    # Average durations
    durations = [t.duration.total_seconds() / 3600 for t in trades]

    return {
        'total_trades': len(trades),
        'winners': len(winners),
        'losers': len(losers),
        'win_rate': len(winners) / len(trades) * 100,
        'gross_profit': gross_profit,
        'gross_loss': gross_loss,
        'net_profit': net_profit,
        'profit_factor': gross_profit / gross_loss if gross_loss > 0 else float('inf'),
        'avg_win': gross_profit / len(winners) if winners else 0,
        'avg_loss': -gross_loss / len(losers) if losers else 0,
        'largest_win': max(t.net_profit for t in winners) if winners else 0,
        'largest_loss': min(t.net_profit for t in losers) if losers else 0,
        'max_drawdown': max_dd,
        'max_drawdown_pct': max_dd_pct,
        'max_win_streak': max_win_streak,
        'max_lose_streak': max_lose_streak,
        'avg_duration_hours': sum(durations) / len(durations),
        'equity_curve': equity,
        'weekday_stats': weekday_stats,
        'symbol_stats': symbol_stats,
        'start_date': trades[0].close_time,
        'end_date': trades[-1].close_time,
    }


# ─── CHART GENERATION ─────────────────────────────────────────

def generate_charts(stats: Dict, trades: List[Trade], output_dir: str) -> List[str]:
    """Generate matplotlib charts, return list of filenames."""
    if not HAS_MATPLOTLIB:
        return []

    charts = []
    plt.style.use('dark_background')

    # 1. Equity Curve
    fig, ax = plt.subplots(figsize=(10, 4))
    ax.plot(stats['equity_curve'], color='#00bcd4', linewidth=1.5)
    ax.fill_between(range(len(stats['equity_curve'])), stats['equity_curve'],
                     stats['equity_curve'][0], alpha=0.1, color='#00bcd4')
    ax.set_title('Equity Curve', fontsize=14, fontweight='light')
    ax.set_xlabel('Trade #')
    ax.set_ylabel('Balance')
    ax.grid(alpha=0.2)
    path = os.path.join(output_dir, 'equity_curve.png')
    fig.savefig(path, dpi=100, bbox_inches='tight', facecolor='#1a1a2e')
    plt.close()
    charts.append('equity_curve.png')

    # 2. Win/Loss Distribution
    fig, ax = plt.subplots(figsize=(10, 4))
    profits = [t.net_profit for t in trades]
    colors = ['#4caf50' if p > 0 else '#f44336' for p in profits]
    ax.bar(range(len(profits)), profits, color=colors, width=0.8)
    ax.axhline(y=0, color='white', linewidth=0.5, alpha=0.5)
    ax.set_title('Profit/Loss per Trade', fontsize=14, fontweight='light')
    ax.set_xlabel('Trade #')
    ax.set_ylabel('P/L')
    ax.grid(alpha=0.2)
    path = os.path.join(output_dir, 'pnl_distribution.png')
    fig.savefig(path, dpi=100, bbox_inches='tight', facecolor='#1a1a2e')
    plt.close()
    charts.append('pnl_distribution.png')

    # 3. Weekday Performance
    days_order = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
    day_data = [(d, stats['weekday_stats'].get(d, {}).get('net', 0)) for d in days_order]
    fig, ax = plt.subplots(figsize=(8, 4))
    days, vals = zip(*day_data)
    colors = ['#4caf50' if v > 0 else '#f44336' for v in vals]
    ax.bar(days, vals, color=colors)
    ax.set_title('Performance by Weekday', fontsize=14, fontweight='light')
    ax.set_ylabel('Net P/L')
    ax.grid(alpha=0.2)
    path = os.path.join(output_dir, 'weekday_performance.png')
    fig.savefig(path, dpi=100, bbox_inches='tight', facecolor='#1a1a2e')
    plt.close()
    charts.append('weekday_performance.png')

    return charts


# ─── HTML REPORT ───────────────────────────────────────────────

def generate_html(stats: Dict, charts: List[str], output_path: str):
    """Generate HTML report."""
    chart_html = ""
    for chart in charts:
        chart_html += f'<img src="{chart}" style="width:100%;max-width:800px;margin:20px 0;border-radius:8px;">\n'

    # Weekday table
    weekday_rows = ""
    for day in ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']:
        d = stats['weekday_stats'].get(day, {'trades': 0, 'net': 0, 'avg': 0, 'win_rate': 0})
        color = '#4caf50' if d['net'] > 0 else '#f44336'
        weekday_rows += f"""<tr>
            <td>{day}</td><td>{d['trades']}</td>
            <td style="color:{color}">{d['net']:.2f}</td>
            <td>{d['win_rate']:.1f}%</td>
        </tr>"""

    # Symbol table
    symbol_rows = ""
    for sym, d in sorted(stats['symbol_stats'].items(), key=lambda x: x[1]['net'], reverse=True):
        color = '#4caf50' if d['net'] > 0 else '#f44336'
        symbol_rows += f"""<tr>
            <td>{sym}</td><td>{d['trades']}</td>
            <td style="color:{color}">{d['net']:.2f}</td>
            <td>{d['win_rate']:.1f}%</td>
        </tr>"""

    html = f"""<!DOCTYPE html>
<html><head><meta charset="utf-8">
<title>Trade Journal Report</title>
<style>
    body {{ font-family: -apple-system, sans-serif; background: #0d1117; color: #c9d1d9; padding: 40px; max-width: 900px; margin: 0 auto; }}
    h1 {{ color: #58a6ff; font-weight: 300; }}
    h2 {{ color: #8b949e; font-weight: 400; margin-top: 40px; }}
    .stats {{ display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; margin: 20px 0; }}
    .stat {{ background: #161b22; border: 1px solid #30363d; border-radius: 8px; padding: 16px; }}
    .stat-label {{ font-size: 12px; color: #8b949e; text-transform: uppercase; }}
    .stat-value {{ font-size: 24px; font-weight: 600; margin-top: 4px; }}
    .green {{ color: #4caf50; }}
    .red {{ color: #f44336; }}
    table {{ width: 100%; border-collapse: collapse; margin: 16px 0; }}
    th, td {{ padding: 8px 12px; text-align: left; border-bottom: 1px solid #30363d; }}
    th {{ color: #8b949e; font-size: 12px; text-transform: uppercase; }}
    .footer {{ margin-top: 40px; padding-top: 20px; border-top: 1px solid #30363d; color: #8b949e; font-size: 12px; }}
</style></head><body>
<h1>Trade Journal Report</h1>
<p>{stats['start_date'].strftime('%Y-%m-%d')} to {stats['end_date'].strftime('%Y-%m-%d')}</p>

<div class="stats">
    <div class="stat"><div class="stat-label">Total Trades</div><div class="stat-value">{stats['total_trades']}</div></div>
    <div class="stat"><div class="stat-label">Win Rate</div><div class="stat-value {'green' if stats['win_rate'] > 50 else 'red'}">{stats['win_rate']:.1f}%</div></div>
    <div class="stat"><div class="stat-label">Profit Factor</div><div class="stat-value {'green' if stats['profit_factor'] > 1 else 'red'}">{stats['profit_factor']:.2f}</div></div>
    <div class="stat"><div class="stat-label">Net Profit</div><div class="stat-value {'green' if stats['net_profit'] > 0 else 'red'}">{stats['net_profit']:.2f}</div></div>
    <div class="stat"><div class="stat-label">Max Drawdown</div><div class="stat-value red">{stats['max_drawdown']:.2f} ({stats['max_drawdown_pct']:.1f}%)</div></div>
    <div class="stat"><div class="stat-label">Avg Win / Loss</div><div class="stat-value">{stats['avg_win']:.2f} / {stats['avg_loss']:.2f}</div></div>
    <div class="stat"><div class="stat-label">Best Streak</div><div class="stat-value green">{stats['max_win_streak']} wins</div></div>
    <div class="stat"><div class="stat-label">Worst Streak</div><div class="stat-value red">{stats['max_lose_streak']} losses</div></div>
</div>

<h2>Charts</h2>
{chart_html}

<h2>Performance by Weekday</h2>
<table><tr><th>Day</th><th>Trades</th><th>Net P/L</th><th>Win Rate</th></tr>{weekday_rows}</table>

<h2>Performance by Symbol</h2>
<table><tr><th>Symbol</th><th>Trades</th><th>Net P/L</th><th>Win Rate</th></tr>{symbol_rows}</table>

<div class="footer">Generated by Trade Journal Analyzer | KruegerAlgorithms</div>
</body></html>"""

    with open(output_path, 'w', encoding='utf-8') as f:
        f.write(html)


# ─── MAIN ──────────────────────────────────────────────────────

def main():
    parser = argparse.ArgumentParser(description='Trade Journal Analyzer')
    parser.add_argument('file', help='CSV file with trade history')
    parser.add_argument('--output', '-o', default='trade_report.html', help='Output HTML file')
    parser.add_argument('--balance', '-b', type=float, default=10000, help='Initial balance')
    args = parser.parse_args()

    if not os.path.exists(args.file):
        print(f"Error: File not found: {args.file}")
        sys.exit(1)

    print(f"Loading trades from {args.file}...")
    trades = load_trades(args.file)

    if not trades:
        print("Error: No trades found in file. Check CSV format.")
        sys.exit(1)

    print(f"Loaded {len(trades)} trades")

    stats = calculate_stats(trades, args.balance)

    output_dir = os.path.dirname(os.path.abspath(args.output)) or '.'
    charts = generate_charts(stats, trades, output_dir)

    generate_html(stats, charts, args.output)
    print(f"\nReport generated: {args.output}")
    print(f"  Trades: {stats['total_trades']} | Win Rate: {stats['win_rate']:.1f}% | "
          f"PF: {stats['profit_factor']:.2f} | Net: {stats['net_profit']:.2f}")


if __name__ == '__main__':
    main()
