"""
Trading Signals models for the crypto trading platform.
"""
from datetime import time

from django.db import models
from django.contrib.auth import get_user_model

User = get_user_model()


class Coin(models.Model):
    """
    Model to store cryptocurrency information.
    """
    name = models.CharField(max_length=100)
    symbol = models.CharField(max_length=20)
    current_price = models.DecimalField(max_digits=20, decimal_places=8, default=0)
    image = models.ImageField(upload_to='coin_images/', null=True, blank=True)
    description = models.TextField(blank=True)
    is_active = models.BooleanField(default=True)
    is_featured = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        verbose_name = 'Coin'
        verbose_name_plural = 'Coins'
        ordering = ['name']
    
    def __str__(self):
        return f"{self.name} ({self.symbol})"


class SignalType(models.TextChoices):
    BUY = 'BUY', 'Buy'
    SELL = 'SELL', 'Sell'


class SignalStatus(models.TextChoices):
    ACTIVE = 'ACTIVE', 'Active'
    COMPLETED = 'COMPLETED', 'Completed'
    CANCELLED = 'CANCELLED', 'Cancelled'
    EXPIRED = 'EXPIRED', 'Expired'


class TradingSignal(models.Model):
    """
    Model to store trading signals created by admin.
    """
    coin = models.ForeignKey(Coin, on_delete=models.CASCADE, related_name='signals')
    signal_type = models.CharField(max_length=10, choices=SignalType.choices)
    entry_price = models.DecimalField(max_digits=20, decimal_places=8)
    target_price = models.DecimalField(max_digits=20, decimal_places=8)
    stop_loss = models.DecimalField(max_digits=20, decimal_places=8)
    status = models.CharField(max_length=20, choices=SignalStatus.choices, default=SignalStatus.ACTIVE)
    description = models.TextField(blank=True)
    notes = models.TextField(blank=True)
    
    # Results (filled when signal is completed)
    result_price = models.DecimalField(max_digits=20, decimal_places=8, null=True, blank=True)
    result_percentage = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
    
    # Admin fields
    created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='created_signals')
    
    # Timestamps
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    completed_at = models.DateTimeField(null=True, blank=True)
    
    class Meta:
        verbose_name = 'Trading Signal'
        verbose_name_plural = 'Trading Signals'
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.coin.name} - {self.signal_type} @ {self.entry_price}"
    
    def calculate_result(self):
        """Calculate the result percentage when signal is completed."""
        if self.result_price and self.entry_price:
            if self.signal_type == SignalType.BUY:
                self.result_percentage = ((self.result_price - self.entry_price) / self.entry_price) * 100
            else:
                self.result_percentage = ((self.entry_price - self.result_price) / self.entry_price) * 100
    
    def get_potential_profit_percentage(self):
        """Calculate potential profit percentage."""
        if self.entry_price and self.target_price:
            return ((self.target_price - self.entry_price) / self.entry_price) * 100
        return 0
    
    def get_risk_percentage(self):
        """Calculate risk percentage."""
        if self.entry_price and self.stop_loss:
            return ((self.entry_price - self.stop_loss) / self.entry_price) * 100
        return 0


class AutomatedSignalPlanStatus(models.TextChoices):
    ACTIVE = 'ACTIVE', 'Active'
    COMPLETED = 'COMPLETED', 'Completed'
    CANCELLED = 'CANCELLED', 'Cancelled'


class AutomatedUserSignalStatus(models.TextChoices):
    PENDING = 'PENDING', 'Pending'
    ACCEPTED = 'ACCEPTED', 'Accepted'
    EXPIRED = 'EXPIRED', 'Expired'
    CANCELLED = 'CANCELLED', 'Cancelled'


class SignalProgramSettings(models.Model):
    """
    Admin-configurable settings for automated user profit signals.
    """
    is_enabled = models.BooleanField(default=True)
    target_multiplier = models.DecimalField(max_digits=5, decimal_places=2, default=2.00)
    completion_days = models.PositiveIntegerField(default=35)
    daily_signal_time = models.TimeField(default=time(19, 0))
    signal_expiry_minutes = models.PositiveIntegerField(default=10)
    test_mode_enabled = models.BooleanField(default=False)
    test_interval_minutes = models.PositiveIntegerField(default=5)
    show_dashboard_market_overview = models.BooleanField(default=True)
    dashboard_market_title = models.CharField(max_length=120, default='Trading Markets')
    telegram_channel_enabled = models.BooleanField(default=False)
    telegram_channel_title = models.CharField(max_length=120, default='Join Our Telegram Channel')
    telegram_channel_description = models.CharField(
        max_length=255,
        blank=True,
        default='Get market updates, alerts, and announcements directly on Telegram.',
    )
    telegram_button_text = models.CharField(max_length=50, default='Open Telegram')
    telegram_channel_url = models.URLField(blank=True)
    telegram_contact_username = models.CharField(max_length=100, blank=True, default='')
    default_coin = models.ForeignKey(
        Coin,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='signal_program_settings',
    )
    default_signal_type = models.CharField(max_length=10, choices=SignalType.choices, default=SignalType.BUY)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = 'Signal Program Setting'
        verbose_name_plural = 'Signal Program Settings'

    def __str__(self):
        return 'Signal Program Settings'


class UserSignalPlan(models.Model):
    """
    Tracks a user's approved deposit target plan for automated signals.
    """
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='signal_plans')
    deposit = models.OneToOneField(
        'deposits.Deposit',
        on_delete=models.CASCADE,
        related_name='signal_plan',
    )
    principal_amount = models.DecimalField(max_digits=15, decimal_places=2)
    target_multiplier = models.DecimalField(max_digits=5, decimal_places=2, default=2.00)
    target_amount = models.DecimalField(max_digits=15, decimal_places=2)
    target_profit_amount = models.DecimalField(max_digits=15, decimal_places=2)
    credited_profit_amount = models.DecimalField(max_digits=15, decimal_places=2, default=0.00)
    daily_profit_amount = models.DecimalField(max_digits=15, decimal_places=2)
    completion_days = models.PositiveIntegerField(default=35)
    accepted_days = models.PositiveIntegerField(default=0)
    status = models.CharField(
        max_length=20,
        choices=AutomatedSignalPlanStatus.choices,
        default=AutomatedSignalPlanStatus.ACTIVE,
    )
    started_at = models.DateTimeField()
    completed_at = models.DateTimeField(null=True, blank=True)
    cancelled_at = models.DateTimeField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = 'User Signal Plan'
        verbose_name_plural = 'User Signal Plans'
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.user.username} - Deposit #{self.deposit_id} - {self.status}"


class AutomatedUserSignal(models.Model):
    """
    Daily automated signal generated for a user's active plan.
    """
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='automated_signals')
    plan = models.ForeignKey(UserSignalPlan, on_delete=models.CASCADE, related_name='daily_signals')
    coin = models.ForeignKey(Coin, on_delete=models.SET_NULL, null=True, blank=True, related_name='automated_signals')
    signal_type = models.CharField(max_length=10, choices=SignalType.choices, default=SignalType.BUY)
    signal_date = models.DateField()
    slot_key = models.CharField(max_length=40, default='', blank=True)
    day_number = models.PositiveIntegerField(default=1)
    scheduled_for = models.DateTimeField()
    expires_at = models.DateTimeField()
    accepted_at = models.DateTimeField(null=True, blank=True)
    status = models.CharField(
        max_length=20,
        choices=AutomatedUserSignalStatus.choices,
        default=AutomatedUserSignalStatus.PENDING,
    )
    profit_amount = models.DecimalField(max_digits=15, decimal_places=2)
    entry_price = models.DecimalField(max_digits=20, decimal_places=8, default=0)
    target_price = models.DecimalField(max_digits=20, decimal_places=8, default=0)
    stop_loss = models.DecimalField(max_digits=20, decimal_places=8, default=0)
    transaction = models.OneToOneField(
        'wallet.Transaction',
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='automated_signal',
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = 'Automated User Signal'
        verbose_name_plural = 'Automated User Signals'
        ordering = ['-scheduled_for', '-created_at']
        constraints = [
            models.UniqueConstraint(fields=['plan', 'slot_key'], name='unique_plan_signal_per_slot'),
        ]

    def __str__(self):
        return f"{self.user.username} - {self.signal_date} - {self.status}"
