import csv
from pathlib import Path
from collections import defaultdict

# Try both likely locations
candidates = [
    Path(r"C:\Users\Administrator\OneDrive\fx_macro_intraday\data\processed\trades\trades_real_costs.csv"),
    Path(r"C:\Users\paul_\OneDrive\fx_macro_intraday\data\processed\trades\trades_real_costs.csv"),
]
p = next((c for c in candidates if c.exists()), None)
if p is None:
    print("Not found at either path. Checked:")
    for c in candidates:
        print(f"  {c}")
    raise SystemExit(1)

print(f"FILE: {p}")
print("=" * 72)
with open(p, newline="", encoding="utf-8") as f:
    rows = list(csv.reader(f))
header = rows[0]
print(f"Rows (incl header): {len(rows)}")
print(f"Columns: {header}")
print()

# Show first 3 data rows to confirm it's EURUSD (prices ~1.1x)
print("First 3 data rows:")
for r in rows[1:4]:
    print("  " + " | ".join(r))
print()

def find_col(cands):
    for i, h in enumerate(header):
        if h.strip().lower() in cands:
            return i
    return None

yi = find_col({"year"})
mi = find_col({"month"})
pnl_i = None
for pref in ["pnl_real", "pnl", "dollar_pnl_real", "pnl_bt"]:
    pnl_i = find_col({pref})
    if pnl_i is not None:
        pnl_name = pref
        break

if yi is not None and mi is not None and pnl_i is not None:
    monthly = defaultdict(float)
    count = defaultdict(int)
    for r in rows[1:]:
        if len(r) <= max(yi, mi, pnl_i):
            continue
        try:
            y=int(r[yi]); m=int(r[mi]); v=float(r[pnl_i])
        except ValueError:
            continue
        monthly[(y,m)] += v
        count[(y,m)] += 1
    print(f"Using pnl column: '{pnl_name}'")
    print(f"Total trades: {sum(count.values())}")
    print("Recent months (2025-2026):")
    for (y,m) in sorted(monthly.keys()):
        if y >= 2025:
            print(f"  {y}-{m:02d}:  {monthly[(y,m)]:>10.2f}  ({count[(y,m)]} trades)")
    yearly = defaultdict(float)
    for (y,m),v in monthly.items():
        yearly[y]+=v
    print("Yearly totals:")
    for y in sorted(yearly.keys()):
        print(f"  {y}: {yearly[y]:>12.2f}")
else:
    print(f"Could not find year/month/pnl. year_i={yi} month_i={mi} pnl_i={pnl_i}")
