from __future__ import annotations

from datetime import date, datetime
from enum import Enum

from pydantic import BaseModel, Field


class ReportType(str, Enum):
    DAILY = "daily"
    WEEKLY = "weekly"


class ValidationStatus(str, Enum):
    PASSED = "passed"
    WARNINGS = "warnings"


class ValidationWarning(BaseModel):
    field_name: str
    computed_value: float
    snapshot_value: float
    pct_difference: float


class PLSection(BaseModel):
    realized_pnl: float
    unrealized_pnl: float
    daily_return: float
    cumulative_return: float
    win_count: int
    loss_count: int
    win_rate: float
    profit_factor: float
    sharpe_ratio: float
    summary: str = ""
    validation_warnings: list[ValidationWarning] = Field(default_factory=list)


class RecommendationAccuracySection(BaseModel):
    total_evaluated: int
    act_count: int
    skip_count: int
    acted_win_rate: float
    avg_confidence_acted: float
    avg_confidence_skipped: float
    summary: str = ""
    validation_warnings: list[ValidationWarning] = Field(default_factory=list)


class PositionDetail(BaseModel):
    ticker: str
    entry_price: float
    current_or_exit_price: float
    pnl: float
    pnl_pct: float
    hold_duration_hours: float
    status: str  # "open" or "closed"


class PositionPerformanceSection(BaseModel):
    positions: list[PositionDetail] = Field(default_factory=list)
    summary: str = ""


class RiskMetricsSection(BaseModel):
    current_risk_tier: str
    portfolio_heat: float
    max_drawdown: float
    current_drawdown_pct: float
    reserve_pool_balance: float
    circuit_breaker_event_count: int
    summary: str = ""


class ModelQualityWindow(BaseModel):
    lookback: str
    win_rate: float | None
    directional_accuracy: float | None
    information_coefficient: float | None
    calibration_error: float | None
    brier_score: float | None


class ModelQualitySection(BaseModel):
    windows: list[ModelQualityWindow] = Field(default_factory=list)
    summary: str = ""
    validation_warnings: list[ValidationWarning] = Field(default_factory=list)


class ReportData(BaseModel):
    """Top-level report structure stored as JSONB."""

    pnl: PLSection
    recommendation_accuracy: RecommendationAccuracySection
    position_performance: PositionPerformanceSection
    risk_metrics: RiskMetricsSection
    model_quality: ModelQualitySection
    executive_summary: str = ""
    validation_status: ValidationStatus = ValidationStatus.PASSED
    generated_at: datetime
    period_start: date
    period_end: date
    report_type: ReportType
