# ================================================================
# services/forecasting/app/models/predictions.py
# ================================================================
"""
Additional prediction models for the forecasting service
"""

from sqlalchemy import Column, String, Integer, Float, DateTime, Boolean, Text, JSON
from sqlalchemy.dialects.postgresql import UUID
from datetime import datetime, timezone
import uuid

from shared.database.base import Base

class ModelPerformanceMetric(Base):
    """Track model performance over time"""
    __tablename__ = "model_performance_metrics"
    
    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    model_id = Column(UUID(as_uuid=True), nullable=False, index=True)
    tenant_id = Column(UUID(as_uuid=True), nullable=False, index=True)
    inventory_product_id = Column(UUID(as_uuid=True), nullable=False)  # Reference to inventory service
    
    # Performance metrics
    mae = Column(Float)  # Mean Absolute Error
    mape = Column(Float)  # Mean Absolute Percentage Error
    rmse = Column(Float)  # Root Mean Square Error
    accuracy_score = Column(Float)
    
    # Evaluation period
    evaluation_date = Column(DateTime(timezone=True), nullable=False)
    evaluation_period_start = Column(DateTime(timezone=True))
    evaluation_period_end = Column(DateTime(timezone=True))
    
    # Metadata
    sample_size = Column(Integer)
    created_at = Column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc))
    
    def __repr__(self):
        return f"<ModelPerformanceMetric(model_id={self.model_id}, mae={self.mae})>"

class PredictionCache(Base):
    """Cache frequently requested predictions"""
    __tablename__ = "prediction_cache"
    
    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    cache_key = Column(String(255), unique=True, nullable=False, index=True)
    
    # Cached data
    tenant_id = Column(UUID(as_uuid=True), nullable=False, index=True)
    inventory_product_id = Column(UUID(as_uuid=True), nullable=False)  # Reference to inventory service
    location = Column(String(255), nullable=False)
    forecast_date = Column(DateTime(timezone=True), nullable=False)
    
    # Cached results
    predicted_demand = Column(Float, nullable=False)
    confidence_lower = Column(Float, nullable=False)
    confidence_upper = Column(Float, nullable=False)
    model_id = Column(UUID(as_uuid=True), nullable=False)
    
    # Cache metadata
    created_at = Column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc))
    expires_at = Column(DateTime(timezone=True), nullable=False)
    hit_count = Column(Integer, default=0)
    
    def __repr__(self):
        return f"<PredictionCache(key={self.cache_key}, inventory_product_id={self.inventory_product_id})>"
