import copy
import json
import os
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
STATE = ROOT / "state"
REPORTS = ROOT / "reports"

DEFAULT_PARAMS = {
    # Strategy v1: the approach shown in the NEXUS dashboard video.
    "supertrend_period": 10,
    "supertrend_mult": 3.0,
    "rsi_period": 14,
    "rsi_ob": 70,
    "rsi_os": 30,
    "ema_trend": 50,
    "vol_ma": 20,
    "min_confidence": 80,      # percent of the 5 factors that must agree
    "min_adx": 0,              # 0 = off
    "mtf_confirm": True,       # higher timeframes must agree
    "higher_tfs": ["1h", "4h"],
    "sides": ["BUY", "SELL"],
    "atr_stop_mult": 1.5,
    "rr": 2.0,                 # 1:2 risk to reward
    "risk_pct": 0.01,          # 1% of account per trade
    "max_bars_held": 96,
}


BASE = {
    "symbol": "BTC/USDT", "exchange": "binance", "platform": "ccxt", "mode": "sim", "market_type": "swap",
    "demo_style": "sandbox", "quote_currency": "USDT", "primary_timeframe": "15m", "candles": 500,
    "poll_seconds": 30, "sim_start_balance": 10000, "fee_rate": 0.0006, "slippage_bps": 2,
    "live_enabled": False, "reuse_demo_account": False,
    "brain": {
        "mode": "shadow",                 # off | shadow (record + measure, no effect) | active (may skip / shrink trades)
        "providers": ["groq", "gemini"],  # order of preference; the next one is used if one fails
        "models": {                       # preferred models; if none exist the best available one is auto-picked
            "groq": ["llama-3.3-70b-versatile", "openai/gpt-oss-120b", "llama-3.1-8b-instant"],
            "gemini": ["gemini-3.6-flash", "gemini-3.5-flash", "gemini-2.5-flash"],
        },
        "review_timeout": 8, "research_timeout": 45, "research_minutes": 60, "max_calls_per_day": 300,
        "reject_min_confidence": 65, "on_error": "proceed",
        "news_blackout": True, "blackout_before_min": 30, "blackout_after_min": 15,
        "postmortems": True, "research": True,
    },
    "risk": {"max_daily_loss_pct": 3.0, "max_leverage": 1.0, "cooldown_minutes": 30, "max_margin_pct": 20},
    "failure": {"max_drawdown_pct": 10.0, "min_trades_before_profit_check": 20, "min_profit_factor": 0.8, "max_versions": 10},
    "gate": {"min_trades": 100, "min_days": 21, "min_profit_factor": 1.3, "max_drawdown_pct": 10.0,
             "backtest_tolerance_r": 0.25, "max_crashes": 0},
}


def _merge(a, b):
    out = copy.deepcopy(a)
    for k, v in (b or {}).items():
        out[k] = _merge(out[k], v) if isinstance(v, dict) and isinstance(out.get(k), dict) else v
    return out


def load_env():
    p = ROOT / ".env"
    if p.exists():
        for line in p.read_text().splitlines():
            line = line.strip()
            if line and not line.startswith("#") and "=" in line:
                k, v = line.split("=", 1)
                os.environ.setdefault(k.strip(), v.strip())


def load(path=None):
    load_env()
    p = Path(path or os.environ.get("SAILAR_CONFIG", ROOT / "config.json"))
    cfg = _merge(BASE, json.loads(p.read_text()))
    cfg["strategy"] = _merge(DEFAULT_PARAMS, cfg.get("strategy"))
    STATE.mkdir(exist_ok=True)
    REPORTS.mkdir(exist_ok=True)
    return cfg
