"""
=========================================
CV6 AI Learning Engine — Database Models
Every completed trade is recorded with
full metadata for ML-style analysis.
=========================================
"""

import json
import time
from sqlalchemy import Column, Float, Integer, String, Text, Boolean
from app.database.base import Base


class TradeRecord(Base):
    """
    Complete record of every trade the autonomous engine executes.
    Used by the learning service to derive patterns and improve.
    """
    __tablename__ = "trade_learning"

    id              = Column(String(16), primary_key=True)

    # ── Symbol & Classification ────────────────────────────────────────────
    symbol          = Column(String(32),  nullable=False, index=True)
    sector          = Column(String(64),  nullable=True)
    style           = Column(String(32),  nullable=False)   # INTRADAY/SWING/FNO/etc.
    broker          = Column(String(64),  nullable=True)

    # ── Trade details ──────────────────────────────────────────────────────
    side            = Column(String(8),   nullable=False)   # BUY | SELL
    qty             = Column(Integer,     default=0)
    entry_price     = Column(Float,       default=0.0)
    exit_price      = Column(Float,       default=0.0)
    stop_loss       = Column(Float,       default=0.0)
    target_price    = Column(Float,       default=0.0)
    pnl             = Column(Float,       default=0.0)
    pnl_pct         = Column(Float,       default=0.0)

    # ── Timing ────────────────────────────────────────────────────────────
    entry_time      = Column(String(32),  nullable=True)
    exit_time       = Column(String(32),  nullable=True)
    holding_minutes = Column(Float,       default=0.0)
    exit_reason     = Column(String(64),  nullable=True)    # TARGET_HIT/STOPPED_OUT/EOD/MANUAL

    # ── Strategy & Indicators ─────────────────────────────────────────────
    strategy        = Column(String(64),  nullable=True)
    indicators_json = Column(Text,        nullable=True)    # JSON blob

    # ── AI Analysis ───────────────────────────────────────────────────────
    ai_models_used  = Column(String(256), nullable=True)    # comma-separated
    ai_signal       = Column(String(16),  nullable=True)    # BUY/SELL/HOLD
    ai_confidence   = Column(Float,       default=0.0)
    ai_correct      = Column(Boolean,     default=False)    # did AI prediction match outcome?
    ai_reason       = Column(Text,        nullable=True)
    from_cache      = Column(Boolean,     default=False)

    # ── Market Context ────────────────────────────────────────────────────
    market_regime   = Column(String(32),  nullable=True)    # BULL/BEAR/SIDEWAYS/VOLATILE
    nifty_pct       = Column(Float,       default=0.0)      # Nifty % change at entry
    sector_pct      = Column(Float,       default=0.0)      # Sector index % change
    vix             = Column(Float,       default=0.0)      # India VIX at entry
    news_sentiment  = Column(String(16),  nullable=True)    # POSITIVE/NEGATIVE/NEUTRAL

    # ── Execution quality ─────────────────────────────────────────────────
    slippage_pct    = Column(Float,       default=0.0)
    execution_ms    = Column(Integer,     default=0)        # order fill time in ms
    mode            = Column(String(16),  default="PAPER")  # PAPER | REAL

    # ── Meta ──────────────────────────────────────────────────────────────
    created_at      = Column(String(32),  nullable=True)

    def get_indicators(self) -> dict:
        if self.indicators_json:
            try:
                return json.loads(self.indicators_json)
            except Exception:
                pass
        return {}

    def set_indicators(self, data: dict) -> None:
        self.indicators_json = json.dumps(data)

    def to_dict(self) -> dict:
        return {
            "id":             self.id,
            "symbol":         self.symbol,
            "sector":         self.sector,
            "style":          self.style,
            "broker":         self.broker,
            "side":           self.side,
            "qty":            self.qty,
            "entry_price":    self.entry_price,
            "exit_price":     self.exit_price,
            "pnl":            round(self.pnl or 0, 2),
            "pnl_pct":        round(self.pnl_pct or 0, 2),
            "entry_time":     self.entry_time,
            "exit_time":      self.exit_time,
            "holding_minutes":self.holding_minutes,
            "exit_reason":    self.exit_reason,
            "strategy":       self.strategy,
            "ai_signal":      self.ai_signal,
            "ai_confidence":  self.ai_confidence,
            "ai_correct":     self.ai_correct,
            "ai_reason":      self.ai_reason,
            "market_regime":  self.market_regime,
            "mode":           self.mode,
            "created_at":     self.created_at,
        }
