#!/usr/bin/env python3
"""
generate_sample_exports.py
Generates synthetic strategy-level CSV exports that match the
schema expected by strategy_registry.py (Part 8).

Produces two files in the exports/ directory:
  - MultiFilter_InSample_EURUSD_H1.csv
  - MultiFilter_OutSample_EURUSD_H1.csv

Usage:
    python generate_sample_exports.py
"""

import os
import random
import pandas as pd
from datetime import datetime, timezone

OUTPUT_DIR = "exports"
os.makedirs(OUTPUT_DIR, exist_ok=True)

random.seed(42)

INDICATORS = ["SMA", "EMA", "KAMA", "SAMA"]
PERIODS    = [10, 12, 14, 16, 18, 20]
SYMBOL     = "EURUSD"
TIMEFRAME  = "H1"


def make_row(phase, indicator, period, run_n=1):
    lr = round(random.uniform(0.01, 0.15), 4) if indicator == "SAMA" else 0.0
    sortino  = round(random.gauss(0.8 if "SAMA" in indicator else 0.5, 0.4), 4)
    profit   = round(random.gauss(600 if sortino > 0 else -200, 300), 2)
    dd       = round(abs(random.gauss(8, 3)), 2)
    trades   = random.randint(30, 120)
    ts       = datetime.now(timezone.utc).strftime("%Y.%m.%d %H:%M:%S")

    return {
        "Test_Phase"           : phase,
        "Symbol"               : SYMBOL,
        "Timeframe"            : TIMEFRAME,
        "Indicator_Name"       : indicator,
        "Filter_Period"        : period,
        "Param_SAMA_LR"        : lr,
        "Net_Profit_USD"       : profit,
        "Sortino_Ratio"        : sortino,
        "Max_Drawdown_Pct"     : dd,
        "Profit_Factor"        : round(max(0.5, random.gauss(1.3, 0.4)), 4),
        "Expected_Payoff"      : round(profit / max(trades, 1), 2),
        "Win_Rate_Pct"         : round(random.uniform(40, 65), 1),
        "Total_Trades"         : trades,
        "Sharpe_Ratio"         : round(sortino * 0.85, 4),
        "Recovery_Factor"      : round(abs(profit) / max(dd * 100, 1), 4),
        "False_Flips_Whipsaws" : random.randint(2, 20),
        "Avg_Lag_On_Turn_Bars" : round(random.uniform(1.5, 6.0), 2),
        "Avg_Dist_Points"      : round(random.uniform(5, 25), 2),
        "Intersection_Freq_Pct": round(random.uniform(10, 40), 1),
        "Avg_Trade_Duration_Hrs": round(random.uniform(4, 48), 2),
        "Market_Share_Time_Pct": round(random.uniform(20, 70), 1),
        "Stability_Over_Years" : random.randint(1, 5),
        "Broker_Server"        : "BrokerA-Server",
        "Account_Currency"     : "USD",
        "Commission_BPS"       : round(random.uniform(0.5, 3.5), 2),
        "Avg_Slippage_Points"  : round(random.uniform(0.5, 3.0), 1),
        "Run_Timestamp_UTC"    : ts,
        "EA_Version"           : "v1.0.0",
        "Run_Unique_ID"        : f"RUN{random.randint(10000, 99999)}",
    }


rows_is  = []
rows_oos = []

for indicator in INDICATORS:
    for period in PERIODS:
        rows_is.append(make_row("InSample",  indicator, period))
        rows_oos.append(make_row("OutSample", indicator, period))

df_is  = pd.DataFrame(rows_is)
df_oos = pd.DataFrame(rows_oos)

path_is  = os.path.join(OUTPUT_DIR, "MultiFilter_InSample_EURUSD_H1.csv")
path_oos = os.path.join(OUTPUT_DIR, "MultiFilter_OutSample_EURUSD_H1.csv")

df_is.to_csv(path_is,  index=False, encoding="utf-8")
df_oos.to_csv(path_oos, index=False, encoding="utf-8")

print(f"[Generator] {len(df_is):,} InSample rows  -> {path_is}")
print(f"[Generator] {len(df_oos):,} OutSample rows -> {path_oos}")
print(f"[Generator] Done. Run strategy_registry.py to ingest.")