"""
Django models for TheStarFX Trading Platform.

Models represent the database schema for:
- Trading bots and automated strategies
- Forex currency pairs and market data
- Educational lessons
- Trading signals and recommendations
- Market news and updates
- User testimonials
- Leaderboard rankings
"""
from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator


class ContentBlock(models.Model):
    """Editable copy and calls-to-action used by public website sections."""

    key = models.SlugField(
        max_length=100,
        unique=True,
        help_text="Stable identifier used by the frontend, for example: home-hero",
    )
    page = models.CharField(max_length=50, db_index=True)
    section = models.CharField(max_length=100)
    eyebrow = models.CharField(max_length=120, blank=True)
    title = models.CharField(max_length=255)
    highlight_text = models.CharField(max_length=255, blank=True)
    body = models.TextField(blank=True)
    primary_cta_label = models.CharField(max_length=80, blank=True)
    primary_cta_url = models.CharField(max_length=255, blank=True)
    secondary_cta_label = models.CharField(max_length=80, blank=True)
    secondary_cta_url = models.CharField(max_length=255, blank=True)
    content_json = models.JSONField(
        default=dict,
        blank=True,
        help_text="Optional structured content such as statistics or feature lists.",
    )
    display_order = models.PositiveIntegerField(default=0, db_index=True)
    is_published = models.BooleanField(default=True, db_index=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True, db_index=True)

    class Meta:
        ordering = ["page", "display_order", "section"]
        indexes = [models.Index(fields=["page", "is_published"])]

    def __str__(self):
        return f"{self.page}: {self.section}"


class SiteSettings(models.Model):
    """Global brand, header and footer settings for the public website."""

    key = models.SlugField(max_length=50, unique=True, default="main")
    site_name = models.CharField(max_length=100, default="TheStarFX")
    site_tagline = models.CharField(max_length=160, blank=True)
    logo_url = models.CharField(max_length=500, blank=True)
    footer_description = models.TextField(blank=True)
    support_email = models.EmailField(blank=True)
    support_location = models.CharField(max_length=160, blank=True)
    copyright_text = models.CharField(max_length=255, blank=True)
    sign_in_label = models.CharField(max_length=40, default="Sign In")
    register_label = models.CharField(max_length=60, default="Get Started")
    learn_menu_label = models.CharField(max_length=40, default="Learn")
    more_menu_label = models.CharField(max_length=40, default="More")
    footer_platform_label = models.CharField(max_length=60, default="Platform")
    footer_learn_label = models.CharField(max_length=60, default="Learn")
    footer_contact_label = models.CharField(max_length=60, default="Contact")
    telegram_url = models.URLField(blank=True)
    discord_url = models.URLField(blank=True)
    x_url = models.URLField(blank=True)
    instagram_url = models.URLField(blank=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name_plural = "site settings"

    def __str__(self):
        return self.site_name


class NavigationItem(models.Model):
    """Ordered links rendered in the public header and footer."""

    LOCATION_CHOICES = [
        ("header_primary", "Header — primary"),
        ("header_learn", "Header — Learn menu"),
        ("header_more", "Header — More menu"),
        ("footer_platform", "Footer — Platform"),
        ("footer_learn", "Footer — Learn"),
        ("footer_legal", "Footer — Legal"),
    ]

    label = models.CharField(max_length=80)
    url = models.CharField(max_length=255)
    location = models.CharField(max_length=30, choices=LOCATION_CHOICES, db_index=True)
    description = models.CharField(max_length=140, blank=True)
    icon = models.CharField(max_length=60, blank=True, help_text="Material Symbols icon name")
    order = models.PositiveIntegerField(default=0, db_index=True)
    is_active = models.BooleanField(default=True, db_index=True)
    open_new_tab = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["location", "order", "id"]
        indexes = [
            models.Index(
                fields=["location", "is_active", "order"],
                name="base_nav_location_active_ord",
            )
        ]

    def __str__(self):
        return f"{self.get_location_display()}: {self.label}"


class Bot(models.Model):
    """Trading bot/automated strategy model."""
    
    STATUS_CHOICES = [
        ('active', 'Active'),
        ('beta', 'Beta'),
        ('inactive', 'Inactive'),
    ]
    
    PLAN_CHOICES = [
        ('Basic', 'Basic'),
        ('Pro', 'Pro'),
        ('VIP', 'VIP'),
    ]
    
    # Basic info
    name = models.CharField(max_length=255, db_index=True)
    description = models.TextField()
    category = models.CharField(max_length=50, db_index=True)
    
    # Trading details
    pairs = models.JSONField(default=list, help_text="Currency pairs the bot trades")
    timeframe = models.CharField(max_length=10, help_text="Trading timeframe (e.g., M5, H1, D1)")
    
    # Performance metrics
    win_rate = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(100)])
    total_trades = models.IntegerField(validators=[MinValueValidator(0)])
    avg_profit = models.FloatField()
    max_drawdown = models.FloatField(validators=[MinValueValidator(0)])
    monthly_return = models.FloatField()
    sharpe_ratio = models.FloatField()
    
    # Pricing and status
    price = models.DecimalField(max_digits=10, decimal_places=2, validators=[MinValueValidator(0)])
    plan = models.CharField(max_length=20, choices=PLAN_CHOICES, db_index=True)
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, db_index=True)
    
    # Metadata
    backtest_years = models.IntegerField(validators=[MinValueValidator(0)])
    badge = models.CharField(max_length=100, blank=True)
    tags = models.JSONField(default=list)
    chart_data = models.JSONField(default=list, help_text="Performance chart data points")
    
    # Timestamps
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['status', 'plan']),
            models.Index(fields=['category', 'status']),
        ]
    
    def __str__(self):
        return f"{self.name} ({self.status})"


class ForexPair(models.Model):
    """Forex currency pair with real-time market data."""
    
    TREND_CHOICES = [
        ('up', 'Uptrend'),
        ('down', 'Downtrend'),
        ('sideways', 'Sideways'),
    ]
    
    CATEGORY_CHOICES = [
        ('major', 'Major'),
        ('cross', 'Cross'),
        ('commodity', 'Commodity'),
        ('exotic', 'Exotic'),
    ]
    
    # Pair identification
    pair = models.CharField(max_length=10, unique=True, db_index=True)
    base = models.CharField(max_length=5)
    quote = models.CharField(max_length=5)
    
    # Market data
    price = models.DecimalField(max_digits=15, decimal_places=5)
    change = models.DecimalField(max_digits=15, decimal_places=6)
    change_pct = models.FloatField()
    bid = models.DecimalField(max_digits=15, decimal_places=5)
    ask = models.DecimalField(max_digits=15, decimal_places=5)
    spread = models.FloatField()
    high = models.DecimalField(max_digits=15, decimal_places=5)
    low = models.DecimalField(max_digits=15, decimal_places=5)
    
    # Volume and metadata
    volume = models.CharField(max_length=50)
    trend = models.CharField(max_length=20, choices=TREND_CHOICES, db_index=True)
    category = models.CharField(max_length=50, choices=CATEGORY_CHOICES, db_index=True)
    sentiment = models.IntegerField(
        validators=[MinValueValidator(0), MaxValueValidator(100)],
        help_text="Sentiment score 0-100"
    )
    
    # Display info
    symbol1 = models.CharField(max_length=10)
    symbol2 = models.CharField(max_length=10)
    color1 = models.CharField(max_length=50)
    color2 = models.CharField(max_length=50)
    
    # Timestamps
    updated_at = models.DateTimeField(auto_now=True)
    created_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        ordering = ['pair']
        indexes = [
            models.Index(fields=['category', 'sentiment']),
            models.Index(fields=['trend']),
        ]
    
    def __str__(self):
        return self.pair


class Lesson(models.Model):
    """Educational content for trading education."""
    
    DIFFICULTY_CHOICES = [
        ('beginner', 'Beginner'),
        ('intermediate', 'Intermediate'),
        ('advanced', 'Advanced'),
    ]
    
    # Content info
    title = models.CharField(max_length=255, db_index=True)
    description = models.TextField()
    category = models.CharField(max_length=50, db_index=True)
    difficulty = models.CharField(max_length=20, choices=DIFFICULTY_CHOICES, db_index=True)
    
    # Media
    image_url = models.URLField()
    video_url = models.URLField(blank=True)
    
    # Content
    content = models.TextField()
    duration_minutes = models.IntegerField(validators=[MinValueValidator(1)])
    order = models.IntegerField(validators=[MinValueValidator(0)])
    tags = models.JSONField(default=list)
    
    # Timestamps
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        ordering = ['order', 'created_at']
        indexes = [
            models.Index(fields=['category', 'difficulty']),
        ]
    
    def __str__(self):
        return self.title


class Signal(models.Model):
    """Trading signal and recommendation."""
    
    SIGNAL_TYPE_CHOICES = [
        ('buy', 'Buy'),
        ('sell', 'Sell'),
        ('hold', 'Hold'),
    ]
    
    # Signal info
    pair = models.CharField(max_length=20, db_index=True)
    signal_type = models.CharField(max_length=10, choices=SIGNAL_TYPE_CHOICES, db_index=True)
    confidence = models.IntegerField(
        validators=[MinValueValidator(0), MaxValueValidator(100)],
        help_text="Signal confidence 0-100"
    )
    
    # Price levels
    entry_price = models.DecimalField(max_digits=15, decimal_places=5)
    stop_loss = models.DecimalField(max_digits=15, decimal_places=5)
    take_profit = models.DecimalField(max_digits=15, decimal_places=5)
    
    # Details
    reason = models.TextField()
    chart_pattern = models.CharField(max_length=100)
    
    # Status
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)
    expires_at = models.DateTimeField(db_index=True)
    
    class Meta:
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['pair', 'signal_type']),
            models.Index(fields=['expires_at']),
        ]
    
    def __str__(self):
        return f"{self.pair} - {self.signal_type} ({self.confidence}%)"


class News(models.Model):
    """Market news and economic events."""
    
    IMPACT_CHOICES = [
        ('high', 'High'),
        ('medium', 'Medium'),
        ('low', 'Low'),
    ]
    
    # Content
    title = models.CharField(max_length=500, db_index=True)
    content = models.TextField()
    source = models.CharField(max_length=100)
    image_url = models.URLField()
    
    # Categorization
    category = models.CharField(max_length=50, db_index=True)
    impact = models.CharField(max_length=20, choices=IMPACT_CHOICES, db_index=True)
    related_pairs = models.JSONField(default=list)
    
    # Timestamps
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)
    published_at = models.DateTimeField(db_index=True)
    
    class Meta:
        ordering = ['-published_at']
        indexes = [
            models.Index(fields=['category', 'impact']),
            models.Index(fields=['source']),
        ]
    
    def __str__(self):
        return self.title


class Testimonial(models.Model):
    """User testimonial and review."""
    
    RATING_CHOICES = [
        (1, '⭐'),
        (2, '⭐⭐'),
        (3, '⭐⭐⭐'),
        (4, '⭐⭐⭐⭐'),
        (5, '⭐⭐⭐⭐⭐'),
    ]
    
    # Author info
    author_name = models.CharField(max_length=255)
    author_title = models.CharField(max_length=255)
    author_image = models.URLField()
    
    # Review
    content = models.TextField()
    rating = models.IntegerField(choices=RATING_CHOICES, validators=[MinValueValidator(1), MaxValueValidator(5)])
    
    # Timestamps
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)
    
    class Meta:
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['rating']),
        ]
    
    def __str__(self):
        return f"{self.author_name} - {self.rating} stars"


class LeaderboardEntry(models.Model):
    """Leaderboard ranking entry."""
    
    # Ranking
    rank = models.IntegerField(validators=[MinValueValidator(1)], db_index=True)
    
    # User info
    user_name = models.CharField(max_length=255, db_index=True)
    avatar = models.URLField()
    
    # Performance metrics
    monthly_return = models.FloatField()
    win_rate = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(100)])
    total_trades = models.IntegerField(validators=[MinValueValidator(0)])
    profit = models.DecimalField(max_digits=15, decimal_places=2)
    
    # Timestamps
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True, db_index=True)
    
    class Meta:
        ordering = ['rank']
        unique_together = [['rank']]
        indexes = [
            models.Index(fields=['user_name']),
        ]
    
    def __str__(self):
        return f"#{self.rank} - {self.user_name}"
