"""
=========================================
CV6 Autonomous Engine — Configuration
All user-defined parameters for the
autonomous AI trading OS.
=========================================
"""

import json
import pathlib
from typing import Dict, List, Optional
from pydantic import BaseModel, Field

_CONFIG_FILE = pathlib.Path(__file__).resolve().parents[2] / "cv6_autonomous_config.json"

_DEFAULT_CONFIG = {
    # Capital
    "total_capital": 100000.0,
    "capital_allocation": {
        "INTRADAY":  30.0,
        "SWING":     25.0,
        "FNO":       20.0,
        "SCALPING":  10.0,
        "LONG_TERM": 15.0,
    },
    # Risk
    "risk_pct": 1.0,
    "max_daily_loss": 2000.0,
    "max_weekly_loss": 8000.0,
    "max_monthly_loss": 20000.0,
    "max_drawdown_pct": 10.0,
    "max_open_positions": 10,
    "max_trades_per_day": 20,
    # Trading time (IST 24h)
    # trading_end = 15:10 → _is_eod() triggers at 15:05 (5 min buffer before MIS SQ at 15:20)
    "trading_start":          "09:15",
    "trading_end":            "15:10",
    # MCX commodity futures close time (evening session ends 23:30, exit by 23:00)
    "commodity_trading_end":  "23:00",
    # Broker allocation per strategy
    "broker_allocation": {
        "INTRADAY":  "AngelOne",
        "SWING":     "AliceBlue",
        "FNO":       "Upstox",
        "SCALPING":  "AngelOne",
        "LONG_TERM": "Zerodha",
    },
    # AI models
    "enabled_ai_models": ["gpt", "claude", "gemini", "deepseek"],
    "ai_mode": "CONSENSUS",
    "consensus_threshold": 60.0,
    "min_models_required": 2,
    "ai_cache_ttl_seconds": 300,
    # Smart Scanner
    "scan_interval_seconds": 30,
    "min_score_to_trade": 65.0,
    "strategies_enabled": ["EMA_CROSSOVER", "VWAP", "SUPERTREND", "RSI_REVERSAL"],
    "use_smart_scanner": True,
    "max_sector_concentration": 30.0,
    # Filters
    "circuit_filter": True,
    "volatility_filter": True,
    "news_filter": True,
    "vix_block_threshold": 22.0,
    # F&O
    "fno_enabled": False,
    "fno_moneyness": "ATM",
    "fno_option_type": "CE",
    # Learning
    "learning_enabled": True,
    "auto_apply_suggestions": False,
    # Mode
    "mode": "PAPER",
}


class CapitalAllocation(BaseModel):
    INTRADAY:  float = 30.0
    SWING:     float = 25.0
    FNO:       float = 20.0
    SCALPING:  float = 10.0
    LONG_TERM: float = 15.0


class BrokerAllocation(BaseModel):
    INTRADAY:  str = "AngelOne"
    SWING:     str = "AliceBlue"
    FNO:       str = "Upstox"
    SCALPING:  str = "AngelOne"
    LONG_TERM: str = "Zerodha"


class AutonomousConfig(BaseModel):
    # ── Capital ────────────────────────────────────────────────────────────────
    total_capital:          float = 100000.0
    capital_allocation:     Dict[str, float] = Field(default_factory=lambda: {
        "INTRADAY": 30.0, "SWING": 25.0, "FNO": 20.0, "SCALPING": 10.0, "LONG_TERM": 15.0,
    })

    # ── Risk ───────────────────────────────────────────────────────────────────
    risk_pct:               float = 1.0
    max_daily_loss:         float = 2000.0
    max_weekly_loss:        float = 8000.0
    max_monthly_loss:       float = 20000.0
    max_drawdown_pct:       float = 10.0
    max_open_positions:     int   = 10
    max_trades_per_day:     int   = 20

    # ── Timing ────────────────────────────────────────────────────────────────
    trading_start:            str   = "09:15"
    trading_end:              str   = "15:10"   # NSE MIS exit (5 min before broker SQ at 15:20)
    commodity_trading_end:    str   = "23:00"   # MCX futures exit (30 min before session end)

    # ── Broker allocation per style ───────────────────────────────────────────
    broker_allocation:      Dict[str, str] = Field(default_factory=lambda: {
        "INTRADAY": "AngelOne", "SWING": "AliceBlue", "FNO": "Upstox",
        "SCALPING": "AngelOne", "LONG_TERM": "Zerodha",
    })

    # ── AI Models ─────────────────────────────────────────────────────────────
    enabled_ai_models:      List[str] = Field(default_factory=lambda: ["gpt", "claude", "gemini", "deepseek"])
    ai_mode:                str   = "CONSENSUS"   # SINGLE | DUAL | TRIPLE | ALL | CONSENSUS
    consensus_threshold:    float = 60.0
    min_models_required:    int   = 2
    ai_cache_ttl_seconds:   int   = 300            # 0 = disable cache

    # ── Smart Scanner (5-stage funnel) ─────────────────────────────────────────
    scan_interval_seconds:  int   = 30
    min_score_to_trade:     float = 65.0
    strategies_enabled:     List[str] = Field(default_factory=lambda: ["EMA_CROSSOVER", "VWAP", "SUPERTREND", "RSI_REVERSAL"])
    use_smart_scanner:      bool  = True           # True = 5-stage funnel; False = basic scanner
    max_sector_concentration: float = 30.0         # % max in one sector

    # ── Filters ───────────────────────────────────────────────────────────────
    circuit_filter:         bool  = True
    volatility_filter:      bool  = True
    news_filter:            bool  = True
    vix_block_threshold:    float = 22.0

    # ── F&O ───────────────────────────────────────────────────────────────────
    fno_enabled:            bool  = False
    fno_moneyness:          str   = "ATM"          # ATM | ITM | OTM
    fno_option_type:        str   = "CE"           # CE | PE | BOTH

    # ── Learning ──────────────────────────────────────────────────────────────
    learning_enabled:       bool  = True
    auto_apply_suggestions: bool  = False

    # ── Mode ──────────────────────────────────────────────────────────────────
    mode:                   str   = "PAPER"        # PAPER | REAL


def load_config() -> AutonomousConfig:
    if _CONFIG_FILE.exists():
        try:
            data = json.loads(_CONFIG_FILE.read_text(encoding="utf-8"))
            return AutonomousConfig(**data)
        except Exception:
            pass
    # Write defaults
    cfg = AutonomousConfig(**_DEFAULT_CONFIG)
    save_config(cfg)
    return cfg


def save_config(cfg: AutonomousConfig) -> None:
    _CONFIG_FILE.write_text(
        json.dumps(cfg.model_dump(), ensure_ascii=False, indent=2),
        encoding="utf-8",
    )
