"""Data models for Mistake Journal."""

from datetime import datetime
from pydantic import BaseModel, Field


class Trade(BaseModel):
    """A trade entry in the journal."""

    id: int
    symbol: str
    action: str  # buy, sell
    entry_price: float
    size: float  # USD value
    entry_date: datetime = Field(default_factory=datetime.now)

    # Pre-trade state
    emotion_level: int = Field(ge=1, le=5, default=3)  # 1=fearful, 5=euphoric
    reasoning: str = ""
    had_plan: bool = False
    stop_loss_set: bool = False
    take_profit_set: bool = False

    # Tags
    tags: list[str] = Field(default_factory=list)
    notes: str = ""

    # Post-close (filled when trade is closed)
    exit_price: float | None = None
    exit_date: datetime | None = None
    reflection: str = ""
    lesson_learned: str = ""

    @property
    def is_closed(self) -> bool:
        return self.exit_price is not None

    @property
    def pnl(self) -> float | None:
        """Profit/loss in USD."""
        if not self.is_closed:
            return None
        if self.action == "buy":
            return self.size * (self.exit_price - self.entry_price) / self.entry_price
        else:  # sell/short
            return self.size * (self.entry_price - self.exit_price) / self.entry_price

    @property
    def pnl_pct(self) -> float | None:
        """Profit/loss as percentage."""
        if not self.is_closed:
            return None
        if self.action == "buy":
            return (self.exit_price - self.entry_price) / self.entry_price * 100
        else:
            return (self.entry_price - self.exit_price) / self.entry_price * 100

    @property
    def is_winner(self) -> bool | None:
        if self.pnl is None:
            return None
        return self.pnl > 0


class MistakePattern(BaseModel):
    """A pattern identified in trading mistakes."""

    tag: str
    trade_count: int
    loss_rate: float  # 0-1
    avg_loss: float
    insights: list[str] = Field(default_factory=list)


class MistakeAnalysis(BaseModel):
    """Analysis of trading patterns and mistakes."""

    total_trades: int
    closed_trades: int
    win_rate: float
    avg_winner: float
    avg_loser: float
    top_mistakes: list[MistakePattern] = Field(default_factory=list)
    recommendations: list[str] = Field(default_factory=list)

    # Emotion correlation
    best_emotion_level: int | None = None
    worst_emotion_level: int | None = None

    # Plan correlation
    win_rate_with_plan: float | None = None
    win_rate_without_plan: float | None = None


# Built-in mistake tags
MISTAKE_TAGS = {
    "fomo": "Fear of missing out - chased a pump",
    "revenge": "Tried to win back losses immediately",
    "no-plan": "Entered without clear entry/exit criteria",
    "no-stop": "No stop loss set",
    "oversized": "Position too large for risk tolerance",
    "overtrading": "Too many trades in short period",
    "averaging-down": "Added to a losing position",
    "moved-stop": "Moved stop loss to avoid being stopped out",
    "early-exit": "Sold winner too early out of fear",
    "held-loser": "Held loser hoping it would recover",
}
