"""Prediction Queue model - antrian beli/jual per hari."""
from datetime import datetime
from app.extensions import db


class PredictionQueue(db.Model):
    """Antrian prediksi beli/jual per hari (Timeline view)."""
    __tablename__ = 'prediction_queues'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    asset_id = db.Column(db.String(100), db.ForeignKey('assets.id', ondelete='CASCADE'),
                        nullable=False)
    prediction_date = db.Column(db.Date, nullable=False)
    sequence_num = db.Column(db.Integer, nullable=False)
    action = db.Column(db.Enum('BUY', 'SELL', name='action_enum'), nullable=False)
    predicted_price = db.Column(db.Numeric(20, 8), nullable=False)
    quantity = db.Column(db.Numeric(20, 8), nullable=False)
    cash_amount = db.Column(db.Numeric(20, 2), nullable=False)
    fee_amount = db.Column(db.Numeric(20, 2), nullable=False)
    profit = db.Column(db.Numeric(20, 2))
    accumulated_units = db.Column(db.Numeric(20, 8))
    accumulated_cash = db.Column(db.Numeric(20, 2))
    confidence = db.Column(db.Numeric(5, 2))
    reason = db.Column(db.String(500))
    algorithm_used = db.Column(db.JSON)
    is_executed = db.Column(db.Boolean, default=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

    asset = db.relationship('Asset', backref=db.backref('predictions', lazy='dynamic'))

    __table_args__ = (
        db.UniqueConstraint('asset_id', 'prediction_date', 'sequence_num',
                            name='uq_prediction'),
        db.Index('idx_pred_date', 'asset_id', 'prediction_date'),
        {},
    )

    def to_dict(self):
        return {
            'id': self.id,
            'asset_id': self.asset_id,
            'prediction_date': str(self.prediction_date),
            'sequence_num': self.sequence_num,
            'action': self.action,
            'predicted_price': float(self.predicted_price),
            'quantity': float(self.quantity),
            'cash_amount': float(self.cash_amount),
            'fee_amount': float(self.fee_amount),
            'profit': float(self.profit) if self.profit else None,
            'accumulated_units': float(self.accumulated_units) if self.accumulated_units else None,
            'accumulated_cash': float(self.accumulated_cash) if self.accumulated_cash else None,
            'confidence': float(self.confidence) if self.confidence else None,
            'reason': self.reason,
            'is_executed': self.is_executed,
        }
