import csv
from pathlib import Path
from collections import defaultdict
from datetime import datetime

base_candidates = [
    Path(r"C:\Users\Administrator\OneDrive\fx_macro_intraday"),
    Path(r"C:\Users\paul_\OneDrive\fx_macro_intraday"),
]
BASE = next((b for b in base_candidates if b.exists()), None)

eu_p = BASE / "data" / "processed" / "trades" / "trades_real_costs.csv"
uj_p = BASE / "data" / "processed" / "usdjpy_trades_real_costs.csv"

def parse_dt(s):
    s = (s or "").strip()
    for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M",
                "%d/%m/%Y %H:%M", "%d/%m/%Y %H:%M:%S"):
        try:
            return datetime.strptime(s[:19], fmt)
        except ValueError:
            continue
    return None

def pick_date_col(fieldnames):
    """Prefer exit_time if present, else entry_time."""
    if "exit_time" in fieldnames:
        return "exit_time"
    if "entry_time" in fieldnames:
        return "entry_time"
    return None

def load(path, pnl_col):
    out = []
    fails = 0
    with open(path, newline="", encoding="utf-8-sig") as f:
        reader = csv.DictReader(f)
        date_col = pick_date_col(reader.fieldnames)
        for r in reader:
            dt = parse_dt(r.get(date_col, ""))
            if dt is None:
                fails += 1
                continue
            try:
                pnl = float(r[pnl_col])
                mae = float(r.get("mae_pct", 0) or 0)
            except (ValueError, KeyError):
                fails += 1
                continue
            out.append((dt, pnl, mae))
    return out, fails, date_col

eu, eu_f, eu_dc = load(eu_p, "dollar_pnl_real")
uj, uj_f, uj_dc = load(uj_p, "pnl_real")
print(f"EU: {len(eu)} trades (failed {eu_f}) using '{eu_dc}'  range {eu[0][0].date()} to {eu[-1][0].date()}")
print(f"UJ: {len(uj)} trades (failed {uj_f}) using '{uj_dc}'  range {uj[0][0].date()} to {uj[-1][0].date()}")
print("\nNOTE: UJ has no exit_time column, only entry_time. Same-day grouping")
print("for UJ uses entry date; EU uses exit date. Close enough for daily-DD")
print("frequency estimate (most trades open and close intraday or within ~1 day).")

def day_stats(trades, label):
    by_day = defaultdict(list)
    for dt, pnl, mae in trades:
        by_day[dt.date()].append(pnl)
    multi = {d: v for d, v in by_day.items() if len(v) > 1}
    worst_day = min(by_day.items(), key=lambda kv: sum(kv[1]))
    print(f"\n{label}:")
    print(f"  Unique trading days: {len(by_day)}")
    print(f"  Days with 2+ trades: {len(multi)} ({len(multi)/len(by_day)*100:.1f}%)")
    print(f"  Worst single day: {sum(worst_day[1]):.2f} on {worst_day[0]} ({len(worst_day[1])} trades)")
    breaches = [(d, sum(v)) for d, v in by_day.items() if sum(v) < -5000]
    print(f"  Days with same-day loss > $5,000: {len(breaches)}")
    for d, tot in sorted(breaches, key=lambda x: x[1])[:6]:
        print(f"    {d}: {tot:.2f}")
    return by_day

eu_days = day_stats(eu, "EURUSD")
uj_days = day_stats(uj, "USDJPY")

combined_by_day = defaultdict(float)
for dt, pnl, mae in eu + uj:
    combined_by_day[dt.date()] += pnl
co_breaches = [(d, t) for d, t in combined_by_day.items() if t < -5000]
print(f"\nCOMBINED (both pairs, same calendar day):")
print(f"  Unique days: {len(combined_by_day)}")
print(f"  Days with combined same-day loss > $5,000 (5% daily DD breach): {len(co_breaches)}")
for d, tot in sorted(co_breaches, key=lambda x: x[1])[:10]:
    print(f"    {d}: {tot:.2f}")

# Also report worst combined day overall
worst_co = min(combined_by_day.items(), key=lambda kv: kv[1])
print(f"\n  Worst combined day: {worst_co[1]:.2f} on {worst_co[0]}")
print(f"  (5% daily limit = -$5,000 at $100k account)")
