"""Long-only Turtle research, bid/ask OHLC or daily proxy. Python 3.11+.

CLI: python turtle_backtest.py --data data --out results
Requires numpy, pandas, matplotlib, and tzdata on platforms without IANA data.
"""
from __future__ import annotations

import argparse
import hashlib
import json
import math
from dataclasses import asdict, dataclass, replace
from pathlib import Path

import numpy as np
import pandas as pd

START = "2016-01-01"
END = "2026-01-01"
TEST = "2022-01-01"
NY = "America/New_York"
SPEC = {
    "XAUUSD": (100., .01, .01, 3.),
    "XAGUSD": (5000., .01, .01, 6.),
    "USATECHIDXUSD": (10., .01, .01, 2.),
    "USA500IDXUSD": (1., .01, .01, 2.),
    "BTCUSD": (1., 1.e-8, 1.e-8, 10.),
    "SPY": (1., 1., 1., 2.),
    "QQQ": (1., 1., 1., 2.),
    "GLD": (1., 1., 1., 3.),
    "SLV": (1., 1., 1., 6.),
}


@dataclass(frozen=True)
class Config:
    entry: int = 20
    exit: int = 10
    atr: int = 20
    multiple: float = 2.
    risk: float = .02
    high_water: bool = True
    leverage: float = 5.
    slippage_bps: float = 1.
    commission_bps: float = .5
    financing_bps: float = 2.
    cost_scale: float = 1.
    granularity: bool = False
    stop_first: bool = True
    flatten_daily: bool = False


ORIGINAL = Config()
REDUCED = Config(risk=.005, high_water=False)


def wilder(tr, period):
    result = np.full(len(tr), np.nan)
    values = tr.to_numpy()
    if len(tr) >= period:
        result[period-1] = np.mean(values[:period])
        for i in range(period, len(tr)):
            result[i] = (result[i-1]*(period-1)+values[i])/period
    return pd.Series(result, index=tr.index)


class Market:
    def __init__(self, path: Path, symbol: str, daily: bool = False):
        self.symbol = symbol
        self.path = path
        self.daily_only = daily
        self.spec = SPEC.get(symbol, (1., .01, .01, 4.))
        p = pd.read_csv(path)
        p.columns = p.columns.str.strip().str.lower()
        p.rename(columns={"time": "timestamp", "datetime": "timestamp", "date": "timestamp"}, inplace=True)
        p["timestamp"] = pd.to_datetime(p["timestamp"], utc=True, format="mixed")
        if all(k in p for k in ("open", "high", "low", "close")) and "bid_open" not in p:
            for key in ("open", "high", "low", "close"):
              p["bid_"+key] = p[key] * (1-self.spec[3]*.5e-4)
              p["ask_"+key] = p[key] * (1+self.spec[3]*.5e-4)
            self.synthetic_spread = True
        else:
            self.synthetic_spread = False
        cols = [side+"_"+k for side in ("bid", "ask") for k in ("open", "high", "low", "close")]
        if p["timestamp"].isna().any() or p["timestamp"].duplicated().any():
            raise ValueError(f"{symbol}: missing or repeated timestamps")
        p = p.sort_values("timestamp", ignore_index=True)
        f = p[cols].to_numpy(dtype=float)
        if not np.isfinite(f).all() or (f <= 0).any():
            raise ValueError(f"{symbol}: missing or nonpositive bar prices")
        for off in (0,4):
            if (f[:,off+1]+1.e-9 < np.maximum(f[:,off], f[:,off+3])).any() or (
                f[:,off+2]-1.e-9 > np.minimum(f[:,off], f[:,off+3])).any():
                raise ValueError(f"{symbol}: malformed OHLC")
        if self.daily_only:
            d = p.timestamp.dt.tz_localize(None).dt.normalize()
        else:
            local = p.timestamp.dt.tz_convert(NY).dt.tz_localize(None)
            d = (local + pd.Timedelta(hours=7)).dt.normalize()
            self.local_minutes = (local.dt.hour*60+local.dt.minute).to_numpy()
        self.f, self.ts = f, pd.DatetimeIndex(p.timestamp)
        self.bar_minutes = float(np.median(np.diff(self.ts.as_unit("ns").asi8))/60.e9) if len(p)>1 else 1440.
        self.prague_dates = self.ts.tz_convert("Europe/Prague").tz_localize(None).normalize().values
        self.starts = np.r_[0, np.flatnonzero(d.values[1:]!=d.values[:-1])+1]
        self.ends = np.r_[self.starts[1:], len(p)]
        self.days = pd.DatetimeIndex(d.iloc[self.starts])
        if not self.days.is_unique:
            raise ValueError(f"{symbol}: multiple bars share same label in daily input")
        self.open = f[self.starts,0]
        self.high = np.maximum.reduceat(f[:,1], self.starts)
        self.low = np.minimum.reduceat(f[:,2], self.starts)
        self.close = f[self.ends-1,3]
        prev = np.r_[self.close[0], self.close[:-1]]
        self.tr = pd.Series(np.maximum.reduce([self.high-self.low, abs(self.high-prev), abs(self.low-prev)]), index=self.days)
        self.level_cache = {}

    def levels(self, cfg):
        key = (cfg.entry,cfg.exit,cfg.atr)
        if key not in self.level_cache:
            self.level_cache[key] = tuple(x.to_numpy() for x in (
              pd.Series(self.high).rolling(cfg.entry).max().shift(),
              pd.Series(self.low).rolling(cfg.exit).min().shift(),
              wilder(self.tr, cfg.atr).shift()))
        return self.level_cache[key]

    def quality(self):
        use = (self.days >= START) & (self.days < END)
        count = np.asarray(self.ends-self.starts)[use]
        dates = self.days[use]
        return dict(symbol=self.symbol, file=self.path.name, daily=self.daily_only,
                    synthetic_spread=self.synthetic_spread,
                    first=str(dates[0].date()), last=str(dates[-1].date()),
                    sessions=int(sum(use)), bars=int(sum(count)),
                    max_session_gap=int(np.diff(dates.values).astype("timedelta64[D]").astype(int).max()),
                    median_bars_per_session=float(np.median(count)), median_bar_minutes=self.bar_minutes,
                    sub_one_hour_sessions=None if self.daily_only else int(sum(count*self.bar_minutes<60)),
                    open_ask_below_bid=int(sum(self.f[:,4]+1e-9 < self.f[:,0])),
                    sha256=hashlib.file_digest(self.path.open("rb"), "sha256").hexdigest())


def first_true(condition):
    if len(condition) and condition.any():
        return int(condition.argmax())
    return None


def run(m: Market, cfg: Config, start=START, end=END, cash=100_000., *, collect_prop=False):
    """Simulation starts flat. Pending intrabar entries are conditioned on bid highs.

    Filled at the worse of open/trigger plus contemporaneous open spread and
    slippage. A closed position cannot reenter until the next strategy session.
    """
    annual, trades, curve, prop = {}, [], [], []
    balance = high_water = float(cash)
    holding = None
    resume = None
    ct, st, at = m.levels(cfg)
    sl = cfg.slippage_bps * 1e-4 * cfg.cost_scale
    cm = cfg.commission_bps * 1e-4 * cfg.cost_scale
    fn = cfg.financing_bps * 1e-4 * cfg.cost_scale
    min_qty = m.spec[0]*m.spec[1]
    step_qty = m.spec[0]*m.spec[2]
    rejected = ambiguous = signals = missed_cutoff = 0
    lag_day = None
    begin = pd.Timestamp(start)
    finish = pd.Timestamp(end)
    begin_day = begin.tz_convert(NY).tz_localize(None)+pd.Timedelta(hours=7) if begin.tzinfo else begin
    finish_day = finish.tz_convert(NY).tz_localize(None)+pd.Timedelta(hours=7) if finish.tzinfo else finish
    first = m.days.searchsorted(begin_day.normalize())
    last = m.days.searchsorted(finish_day.normalize(),side="right") if finish.tzinfo else m.days.searchsorted(finish)
    if collect_prop and m.daily_only:
        raise ValueError("Prop equity replay needs intraday data")
    if cfg.flatten_daily and (m.daily_only or m.bar_minutes>30):
        raise ValueError("Daily flat study needs bars of 30 minutes or finer")

    def mark(price):
        if holding is None:
            return balance
        return balance+holding["qty"]*(price-holding["entry"])

    def event(i, price, opened=False, closed_pnl=0.):
        if collect_prop:
            from prop_eval import EquityEvent
            prop.append(EquityEvent(m.ts[i].to_pydatetime(), balance, mark(price), holding is None,
                                    opened, None, closed_pnl))

    def marks(a, b):
        # Restrict Python events to the worst observed equity each Prague day;
        # the next change in cash/position state terminates the batch.
        if not collect_prop or a >= b:
            return
        bd = m.prague_dates[a:b]
        for lo, hi in zip(np.r_[0,np.flatnonzero(bd[1:]!=bd[:-1])+1],
                          np.r_[np.flatnonzero(bd[1:]!=bd[:-1])+1,len(bd)]):
            k = a+lo+int(m.f[a+lo:a+hi,2].argmin())
            event(k,m.f[k,2])

    def close(i, raw, reason, day):
        nonlocal balance, high_water, holding
        p = raw*(1-sl)
        qty = holding["qty"]
        exit_fee = qty*p*cm
        pnl = qty*(p-holding["entry"])-exit_fee
        balance += pnl
        t = holding.copy()
        t.update(exit_time=m.ts[i].isoformat(), exit_session=str(day.date()), exit_price=p,
                 exit_reason=reason, net=pnl-t["entry_fee"]-t["financing"],
                 risk_r=(pnl-t["entry_fee"]-t["financing"])/t["nominal_risk"],
                 holding_days=int((day-pd.Timestamp(t["session"])).days))
        trades.append(t)
        high_water = max(high_water,balance)
        holding = None
        event(i,raw,closed_pnl=t["net"])

    def enter(i, raw, day, qty, fixed, stop, distance):
        nonlocal balance, holding
        fee = qty*raw*cm
        balance -= fee
        holding = dict(session=str(day.date()), entry_time=m.ts[i].isoformat(),
                       entry=raw, qty=qty, fixed=fixed, stop=stop, entry_fee=fee,
                       financing=0., nominal_risk=qty*distance)

    for j in range(first, last):
        day = m.days[j]
        a, b = m.starts[j], m.ends[j]
        if begin.tzinfo:
            a = max(a,m.ts.searchsorted(begin))
        if finish.tzinfo:
            b = min(b,m.ts.searchsorted(finish,side="left"))
        if a >= b:
            continue
        full_b = b
        if cfg.flatten_daily:
            loc = m.local_minutes[a:b]
            x = (loc>=18*60)|(loc<16*60+30)
            if not x.any():
                continue
            u = int(x.argmax())
            v = len(x)-int(x[::-1].argmax())
            a, b = a+u, a+v
        f = m.f[a:b]
        if resume is not None:
            # Keep virtual stop from the original campaign. On reactivation
            # use at most the same units and enforce the notional cap again.
            next_stop=max(resume["stop"],st[j])
            if f[0,0] > next_stop:
                p=(f[0,0]+max(f[0,4]-f[0,0],0.)*cfg.cost_scale)*(1+sl)
                q=min(resume["qty"],balance*cfg.leverage/(p*(1+cm)))
                if q>0:
                    enter(a,p,day,q,resume["fixed"],next_stop,p-next_stop)
                    event(a,f[0,0],opened=True)
            resume=None
        carried = holding is not None
        if carried:
            cost = 0. if cfg.flatten_daily else (day-lag_day).days*fn*holding["qty"]*m.close[j-1]
            balance -= cost
            holding["financing"] += cost
            event(a,f[0,0])
            holding["stop"] = max(holding["stop"], st[j])
            k = first_true(f[:,2] <= holding["stop"])
            if k is not None:
                marks(a,a+k)
                close(a+k,min(f[k,0],holding["stop"]),
                      "fixed" if holding["stop"]==holding["fixed"] else "donchian",day)
            else:
                marks(a,b)
        if not carried and np.isfinite(ct[j]) and np.isfinite(at[j]) and balance > 0:
            k = first_true(f[:,1] > ct[j])
            if k is not None:
                signals += 1
                spr = max(0., f[k,4]-f[k,0])
                spr *= cfg.cost_scale
                entry_bid = max(ct[j],f[k,0])
                entry = (entry_bid+spr)*(1+sl)
                distance = cfg.multiple*at[j]
                basis = high_water if cfg.high_water else balance
                fixed = entry-distance
                stop = max(fixed,st[j])
                unit = (entry-stop*(1-sl)) + cm*(entry+stop)
                if distance <= 0 or stop <= 0 or unit <= 0:
                    rejected += 1
                    k = None
                else:
                    qty = min(basis*cfg.risk/max(distance,unit), balance*cfg.leverage/(entry*(1+cm)))
                    if cfg.granularity:
                        qty = math.floor(qty/step_qty+1e-12)*step_qty
                    if qty <= 0 or (cfg.granularity and (
                          qty+1e-12<min_qty or (m.symbol=="BTCUSD" and qty*entry<10))):
                        rejected += 1
                        k = None
            if k is not None:
                enter(a+k,entry,day,qty,fixed,stop,distance)
                event(a+k,entry_bid,opened=True)
                if f[k,2] <= stop and f[k,0] <= ct[j]:
                    ambiguous += 1
                at_open = f[k,0] > ct[j]
                scan = k if (cfg.stop_first or at_open) else k+1
                off = first_true(f[scan:,2] <= stop)
                if off is not None:
                    h = scan+off
                    marks(a+k+(0 if cfg.stop_first else 1),a+h)
                    raw = stop if h==k and not at_open else min(f[h,0],stop)
                    close(a+h,raw,"entry_bar_stop" if h==k else ("fixed" if stop==fixed else "donchian"),day)
                else:
                    marks(a+k+(0 if cfg.stop_first else 1),b)
        if cfg.flatten_daily and holding is not None:
            resume=holding.copy()
            if b<full_b and m.local_minutes[b]>=16*60+30:
                close(b,m.f[b,0],"session_flat",day)
            else:
                # Missing cutoff within this feed/session. Use last available
                # pre-cutoff close as a proxy and explicitly count these.
                missed_cutoff += 1
                close(b-1,m.f[b-1,3],"session_flat_proxy",day)
        equity = mark(m.f[full_b-1,3])
        curve.append((day,balance,equity,m.f[full_b-1,3],carried or holding is not None or resume is not None or
                      bool(trades and trades[-1]["session"]==str(day.date()))))
        event(full_b-1,m.f[full_b-1,3])
        lag_day = day
    # No forced final exit: open trades marked on bid, unrealized costs except
    # a hypothetical final commission remain separate from closed-trade data.
    data = pd.DataFrame(curve,columns=["date","balance","equity","bid","invested"]).set_index("date")
    data["invested"] = data["invested"].astype(bool)
    return data, pd.DataFrame(trades), dict(signals=signals,rejected=rejected,ambiguous=ambiguous,
                                           open_at_end=holding is not None, flat_cutoff_proxies=missed_cutoff), prop


def metrics(c, t, initial, seed=311):
    if c.empty:
        return {}
    e = c.equity
    last = float(e.iloc[-1])
    days = (e.index[-1]-e.index[0]).days+1
    peak = e.cummax().clip(lower=initial)
    r = e.pct_change().dropna()
    trade_n = len(t)
    pnl = t.net if trade_n else pd.Series([],dtype=float)
    vol = r.std()
    annualization = (len(e)-1)*365.2425/max(days-1,1)
    # Moving blocks of 20 sessions retain some serial dependence; percentile
    # range describes sample uncertainty, not a forecast or formal edge test.
    ci = None
    if len(r)>=40 and (r>-1).all():
        x = np.log1p(r.to_numpy())
        blocks = np.convolve(x,np.ones(20),mode="valid")
        gen = np.random.default_rng(seed)
        sampled = gen.choice(blocks,size=(1000,max(1,len(x)//20))).mean(axis=1)*annualization/20
        ci = [float(v) for v in np.quantile(np.expm1(sampled),[.025,.975])]
    return dict(final=last, total=last/initial-1, cagr=(last/initial)**(365.2425/days)-1 if last>0 else -1.,
                max_drawdown=float((e/peak-1).min()), sharpe=float(r.mean()/vol*np.sqrt(annualization)) if vol>0 else None,
                trades=trade_n, win_rate=float((pnl>0).mean()) if trade_n else None,
                profit_factor=float(pnl[pnl>0].sum()/-pnl[pnl<0].sum()) if (pnl<0).any() else None,
                median_days=float(t.holding_days.median()) if trade_n else None,
                exposure=float(c.invested.mean()), financing=float(t.financing.sum()) if trade_n else 0.,
                buy_hold=float(c.bid.iloc[-1]/c.bid.iloc[0]-1),
                cagr_block_interval=ci)


def data_inventory(path):
    found = {}
    for item in sorted(path.glob("*.csv*")):
        if not item.name.lower().endswith((".csv", ".csv.gz")):
            continue
        name = item.name.split(".")[0].upper().replace("_COINBASE_86400S","_DAILY").replace("_COINBASE_3600S","_M1")
        for suffix in ("_DAILY","_D1","-DAILY","-D1","_M1","-M1","_5M","_1H","_M5","_HOURLY"):
            if name.endswith(suffix):
                name = name[:-len(suffix)]
                break
        name = {"NQ":"USATECHIDXUSD","SP500":"USA500IDXUSD"}.get(name,name)
        if name not in SPEC:
            continue
        daily = any(s in item.name.lower() for s in ("daily",".d1","_d1","-d1","86400s"))
        if name not in found or not daily:
            found[name]=(item,daily)
    return found


def study(market, out):
    scenarios = {
        "baseline": ORIGINAL,
        "risk_0_5": REDUCED,
        "wide_55_20": replace(REDUCED,entry=55,exit=20),
        "fast_15_7": replace(REDUCED,entry=15,exit=7),
        "risk_0_5_double_cost": replace(REDUCED,cost_scale=2),
        "baseline_alt_fill": replace(ORIGINAL,stop_first=False),
        "personal_0_5": replace(REDUCED,granularity=True),
        "personal_1": replace(REDUCED,risk=.01,granularity=True),
        "personal_0_5_double_cost": replace(REDUCED,granularity=True,cost_scale=2),
    }
    if not market.daily_only and market.bar_minutes<=30:
        scenarios["day_flat_0_5"]=replace(REDUCED,flatten_daily=True)
        scenarios["day_flat_0_5_double_cost"]=replace(REDUCED,flatten_daily=True,cost_scale=2)
    if market.symbol=="BTCUSD":
        # Displayed retail-fee scenario on unleveraged cash spot, not a CFD.
        scenarios={k:replace(v,leverage=1.,commission_bps=60.,financing_bps=0.)
                   for k,v in scenarios.items()}
    collected = {}
    for name,cfg in scenarios.items():
        initial = 1_000 if name.startswith("personal_") else 100_000
        periods = {"full":(START,END),"early":(START,TEST),"late":(TEST,END)}
        for part,(start,end) in periods.items():
            c,t,a,_ = run(market,cfg,start,end,initial)
            if c.empty:
                continue
            key=name+"/"+part
            collected[key]=metrics(c,t,initial)|a
            if part=="full":
                c.to_csv(out/f"{market.symbol}_{name}_equity.csv")
                t.to_csv(out/f"{market.symbol}_{name}_trades.csv",index=False)
    return collected, {key:asdict(value) for key,value in scenarios.items()}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--data",type=Path,default=Path("data"))
    parser.add_argument("--out",type=Path,default=Path("results"))
    parser.add_argument("--symbols",nargs="*")
    a=parser.parse_args()
    a.out.mkdir(parents=True,exist_ok=True)
    datasets=data_inventory(a.data)
    if a.symbols:
        datasets={k:v for k,v in datasets.items() if k in a.symbols}
    if not datasets:
        parser.error("No valid market datasets found. See README.md for data instructions.")
    report={"window":{"start":START,"end_exclusive":END,"late_start":TEST},"markets":{}}
    for symbol,(path,daily) in datasets.items():
        print(f"Reading {symbol} {path}",flush=True)
        market=Market(path,symbol,daily)
        print(market.quality(),flush=True)
        rows, configs = study(market,a.out)
        report["markets"][symbol]={"quality":market.quality(),"scenarios":rows,"configs":configs}
        (a.out/"results.json").write_text(json.dumps(report,indent=2,allow_nan=False),encoding="utf-8")


if __name__=="__main__":
    main()
