import uuid
from django.conf import settings
from django.db import models
from apps.business.schemes.models import OpportunityBundle
from apps.core.models import BaseModel


class PowerStreamConfig(models.Model):
    opportunity_bundle = models.ForeignKey(OpportunityBundle, on_delete=models.CASCADE, related_name='power_stream_configs')
    level = models.PositiveSmallIntegerField()
    amount = models.DecimalField(max_digits=12, decimal_places=2)

    class Meta:
        unique_together = ('opportunity_bundle', 'level')
        ordering = ['opportunity_bundle', 'level']
        indexes = [
            models.Index(fields=['opportunity_bundle', 'level']),
        ]

    def __str__(self):
        return f"PowerStreamConfig(opportunity_bundle={self.opportunity_bundle_id}, level={self.level}, amount={self.amount})"


class PowerStreamBonusRecord(BaseModel):
    """
    Tracks each power stream bonus earned by a user.
    Bonuses are PENDING until claimed. Unclaimed bonuses expire after 30 days.
    """

    class Status(models.TextChoices):
        PENDING = 'PENDING', 'Pending'
        CLAIMED = 'CLAIMED', 'Claimed'
        EXPIRED = 'EXPIRED', 'Expired'     # user did not claim in 30 days
        FORFEITED = 'FORFEITED', 'Forfeited'  # went to company

    earner = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='power_stream_bonuses',
        db_index=True,
    )
    # Distributor ID that earned this (upline earner's distributor)
    earner_distributor = models.ForeignKey(
        'distributor.DistributorID',
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='power_stream_earned',
        db_index=True,
    )
    # Distributor ID that triggered this bonus (the new one that was registered)
    trigger_distributor = models.ForeignKey(
        'distributor.DistributorID',
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='power_stream_triggered',
        db_index=True,
    )
    opportunity_bundle = models.ForeignKey(
        OpportunityBundle,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='power_stream_records',
        db_index=True,
    )
    level = models.PositiveSmallIntegerField()
    gross_amount = models.DecimalField(max_digits=12, decimal_places=2)
    net_amount = models.DecimalField(max_digits=12, decimal_places=2)
    status = models.CharField(max_length=12, choices=Status.choices, default=Status.PENDING, db_index=True)
    earned_at = models.DateTimeField(auto_now_add=True, db_index=True)
    expires_at = models.DateTimeField(db_index=True)
    claimed_at = models.DateTimeField(null=True, blank=True)
    # YYYY-MM string to easily group/deduplicate monthly claims
    claim_period = models.CharField(max_length=7, null=True, blank=True, db_index=True)
    reference_id = models.CharField(max_length=128, unique=True, db_index=True)

    class Meta:
        ordering = ['-earned_at']
        indexes = [
            models.Index(fields=['earner', 'status']),
            models.Index(fields=['earner', 'claim_period']),
            models.Index(fields=['status', 'expires_at']),
        ]

    def __str__(self):
        return f"PSBonus earner={self.earner_id} level={self.level} {self.status} ₹{self.net_amount}"


class PowerStreamMonthlyClaim(BaseModel):
    """
    One record per user per calendar month. Tracks claimed amount and status.
    """

    class Status(models.TextChoices):
        CLAIMED = 'CLAIMED', 'Claimed'
        EXPIRED = 'EXPIRED', 'Expired'

    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='power_stream_monthly_claims',
        db_index=True,
    )
    claim_month = models.CharField(max_length=7, db_index=True)  # YYYY-MM
    total_gross = models.DecimalField(max_digits=12, decimal_places=2, default=0)
    total_net = models.DecimalField(max_digits=12, decimal_places=2, default=0)
    records_count = models.PositiveIntegerField(default=0)
    status = models.CharField(max_length=10, choices=Status.choices, default=Status.CLAIMED)

    class Meta:
        unique_together = ('user', 'claim_month')
        ordering = ['-claim_month']
        indexes = [
            models.Index(fields=['user', 'claim_month']),
        ]

    def __str__(self):
        return f"PSClaim user={self.user_id} month={self.claim_month} ₹{self.total_net} {self.status}"
