"""Flow engine — ManyChat-style branching adaptive learning."""
from django.db import models
from django.conf import settings


class FlowDefinition(models.Model):
    LESSON_TYPE_CHOICES = [
        ('FLOW', '🧭 Flow (ManyChat)'),
        ('STORY', '📖 Story (Text)'),
        ('VIDEO', '🎥 Video (YouTube)'),
        ('WHITEBOARD', '🎨 Whiteboard'),
        ('LIVE', '🔴 Live Class'),
    ]
    lesson_type = models.CharField(max_length=20, choices=LESSON_TYPE_CHOICES, default='FLOW')
    """A teaching flow (like a ManyChat flow)."""
    STATUS_CHOICES = [
        ('DRAFT', 'Draft'),
        ('PUBLISHED', 'Published'),
        ('ARCHIVED', 'Archived'),
    ]
    title = models.CharField(max_length=200)
    subject = models.CharField(max_length=50, blank=True, default='', db_index=True)
    topic = models.CharField(max_length=200, blank=True, default='', db_index=True)
    class_name = models.CharField(max_length=50, blank=True, default='', db_index=True)
    description = models.TextField(blank=True, default='')
    teacher = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, related_name='flows_created')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='DRAFT', db_index=True)
    mastery_threshold = models.PositiveSmallIntegerField(default=4, help_text='Consecutive correct answers to reach mastery')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    is_published = models.BooleanField(default=False)

    medium = models.CharField(
        max_length=2,
        choices=[('EN', 'English'), ('UR', 'Urdu / Roman Urdu')],
        default='EN',
        db_index=True,
        help_text='Instruction medium for this flow content',
    )
    sharjeel_mode = models.CharField(max_length=20, choices=[('MEMORIZE', 'Memorize'), ('UNDERSTAND', 'Understand')], blank=True, default='', db_index=True)
    is_shared_with_academy = models.BooleanField(default=True)

    class Meta:
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.title} ({self.get_status_display()})"


class FlowNode(models.Model):
    """A single node in the flow graph."""
    NODE_TYPE_CHOICES = [
        ('START', '🟢 Start'),
        ('STORY', '📖 Story'),
        ('QUESTION', '❓ Question'),
        ('PRO_LEARNING', '🎓 Pro Learning'),  # Multi-Step Reasoning
        ('CONDITION', '🔀 Condition'),
        ('TIMER', '⏱️ Timer'),
        ('ACTION', '✅ Action'),
        ('END', '🏁 End'),
    ]
    flow = models.ForeignKey(FlowDefinition, on_delete=models.CASCADE, related_name='nodes')
    node_type = models.CharField(max_length=20, choices=NODE_TYPE_CHOICES, db_index=True)
    label = models.CharField(max_length=200, blank=True, default='')
    # Config structure varies by node_type (documented in engine)
    config_json = models.TextField(default='{}', help_text='JSON: node-type-specific config')
    position_x = models.IntegerField(default=100)
    position_y = models.IntegerField(default=100)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['created_at']

    def __str__(self):
        return f"{self.get_node_type_display()} — {self.label or self.pk}"


class FlowEdge(models.Model):
    """A connection from one node to another. First matching path wins (by priority)."""
    flow = models.ForeignKey(FlowDefinition, on_delete=models.CASCADE, related_name='edges')
    source_node = models.ForeignKey(FlowNode, on_delete=models.CASCADE, related_name='outgoing_edges')
    target_node = models.ForeignKey(FlowNode, on_delete=models.CASCADE, related_name='incoming_edges')
    label = models.CharField(max_length=100, blank=True, default='', help_text="e.g. 'correct', 'wrong', 'timeout', 'path_A'")
    priority = models.PositiveSmallIntegerField(default=1, help_text='Lower = checked first')
    condition_json = models.TextField(default='{}', help_text='JSON: rule to evaluate (empty = always match)')

    class Meta:
        ordering = ['priority']

    def __str__(self):
        return f"{self.source_node_id} --[{self.label or self.priority}]--> {self.target_node_id}"


class FlowRun(models.Model):
    """One student's run through a flow."""
    STATUS_CHOICES = [
        ('ACTIVE', 'Active'),
        ('COMPLETED', 'Completed'),
        ('ABANDONED', 'Abandoned'),
    ]
    flow = models.ForeignKey(FlowDefinition, on_delete=models.CASCADE, related_name='runs')
    student = models.ForeignKey('Student', on_delete=models.CASCADE, null=True, blank=True, related_name='flow_runs')
    preview_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name='preview_flow_runs', help_text='Set when a teacher previews their own flow')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='ACTIVE', db_index=True)
    current_node = models.ForeignKey(FlowNode, on_delete=models.SET_NULL, null=True, blank=True, related_name='runs_here')
    state_json = models.TextField(default='{}', help_text='JSON: answers, consecutive_correct, path_taken')
    score = models.PositiveIntegerField(default=0)
    mastery_level = models.CharField(max_length=20, default='LEARNING')
    started_at = models.DateTimeField(auto_now_add=True)
    completed_at = models.DateTimeField(null=True, blank=True)

    class Meta:
        ordering = ['-started_at']

    def __str__(self):
        return f"{self.student.code} → {self.flow.title} ({self.status})"


class FlowRunEvent(models.Model):
    """Audit trail of every action during a run."""
    run = models.ForeignKey(FlowRun, on_delete=models.CASCADE, related_name='events')
    event_type = models.CharField(max_length=30, db_index=True)  # ENTERED, ANSWERED, TIMED_OUT, BRANCHED, COMPLETED
    node = models.ForeignKey(FlowNode, on_delete=models.SET_NULL, null=True, blank=True)
    data_json = models.TextField(default='{}')
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['created_at']


class ChatMessage(models.Model):
    """A chat message in a student's flow run (renders as chat bubbles)."""
    ROLE_CHOICES = [('teacher', 'Teacher'), ('student', 'Student')]
    run = models.ForeignKey(FlowRun, on_delete=models.CASCADE, related_name='chat_messages')
    role = models.CharField(max_length=10, choices=ROLE_CHOICES)
    content = models.TextField()
    message_type = models.CharField(max_length=20, default='text', help_text='text, question, pro_learning, story, feedback')
    metadata_json = models.TextField(default='{}', help_text='options, timer, steps, etc.')
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['created_at']


class ChatMessage(models.Model):
    """A chat message in a student's flow run (renders as chat bubbles)."""
    ROLE_CHOICES = [('teacher', 'Teacher'), ('student', 'Student')]
    run = models.ForeignKey(FlowRun, on_delete=models.CASCADE, related_name='chat_messages')
    role = models.CharField(max_length=10, choices=ROLE_CHOICES)
    content = models.TextField()
    message_type = models.CharField(max_length=20, default='text', help_text='text, question, pro_learning, story, feedback')
    metadata_json = models.TextField(default='{}', help_text='options, timer, steps, etc.')
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['created_at']


class LessonBlock(models.Model):
    """Ordered content block for linear lessons (Story/Video/Lesson types).
    Each block is one piece: text paragraph, video, image, file, or quiz.
    Block editor writes these; student player renders them in order.
    """
    BLOCK_TYPES = [
        ('TEXT', 'Text'),
        ('VIDEO', 'Video'),
        ('IMAGE', 'Image'),
        ('FILE', 'File'),
        ('QUIZ', 'Quiz'),
    ]
    lesson = models.ForeignKey('FlowDefinition', on_delete=models.CASCADE, related_name='lesson_blocks')
    block_type = models.CharField(max_length=10, choices=BLOCK_TYPES, default='TEXT')
    order = models.PositiveIntegerField(default=0)
    title = models.CharField(max_length=200, blank=True, default='')
    content = models.TextField(blank=True, default='')
    url = models.CharField(max_length=500, blank=True, default='')
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['order', 'id']

    def __str__(self):
        return f'{self.get_block_type_display()} - {self.lesson.title}'

class FlowDeletionRequest(models.Model):
    STATUS_CHOICES = [('PENDING', 'Pending'), ('APPROVED', 'Approved'), ('REJECTED', 'Rejected')]
    flow = models.ForeignKey(FlowDefinition, on_delete=models.CASCADE, related_name='deletion_requests')
    student = models.ForeignKey('exams.Student', on_delete=models.CASCADE)
    reason = models.TextField(blank=True, default='')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='PENDING')
    created_at = models.DateTimeField(auto_now_add=True)
    processed_at = models.DateTimeField(null=True, blank=True)
    processed_by = models.ForeignKey('auth.User', null=True, blank=True, on_delete=models.SET_NULL)
