"""
故事模块模型
"""
from django.db import models
from apps.users.models import User


class StoryShelf(models.Model):
    """故事书架"""

    user = models.ForeignKey(
        User, on_delete=models.CASCADE,
        related_name='story_shelves', verbose_name='用户'
    )
    name = models.CharField('书架名称', max_length=100)
    capacity = models.IntegerField('容量上限', default=10)
    is_locked = models.BooleanField('是否加锁', default=False)
    unlock_cost = models.IntegerField('解锁积分', default=0)
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)

    class Meta:
        db_table = 'story_shelf'
        verbose_name = '故事书架'
        verbose_name_plural = verbose_name
        ordering = ['created_at']

    def __str__(self):
        return self.name

    @property
    def is_full(self):
        return self.stories.count() >= self.capacity


class Story(models.Model):
    """故事"""

    GENERATION_MODE_CHOICES = [
        ('ai', 'AI生成'),
        ('manual', '手动创建'),
    ]

    user = models.ForeignKey(
        User, on_delete=models.CASCADE,
        related_name='stories', verbose_name='用户'
    )
    shelf = models.ForeignKey(
        StoryShelf, on_delete=models.SET_NULL,
        related_name='stories', verbose_name='所属书架',
        null=True, blank=True,
    )
    title = models.CharField('标题', max_length=200)
    content = models.TextField('内容', blank=True, default='')
    cover_url = models.URLField('封面URL', max_length=500, blank=True, default='')
    audio_url = models.URLField('音频URL', max_length=500, blank=True, default='')
    opus_url = models.URLField('Opus音频URL', max_length=500, blank=True, default='')
    has_video = models.BooleanField('是否有视频', default=False)
    video_url = models.URLField('视频URL', max_length=500, blank=True, default='')
    generation_mode = models.CharField(
        '生成方式', max_length=20,
        choices=GENERATION_MODE_CHOICES, default='ai'
    )
    prompt = models.TextField('生成提示词', blank=True, default='')
    is_default = models.BooleanField('是否默认故事', default=False)
    intro_opus_data = models.TextField('引导语Opus数据', blank=True, default='')
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)

    class Meta:
        db_table = 'story'
        verbose_name = '故事'
        verbose_name_plural = verbose_name
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['user', 'shelf']),
        ]

    def __str__(self):
        return self.title
