from django.db import models


class Interview(models.Model):
    STATUS_CHOICES = [
        ("pending", "Pending"),
        ("approved", "Approved"),
        ("rejected", "Rejected"),
    ]

    # old fields
    candidate_name = models.CharField(max_length=200)
    jd = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

    # new fields
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default="pending")
    hr_note = models.TextField(blank=True)
    decided_at = models.DateTimeField(null=True, blank=True)
    overall_score = models.FloatField(null=True, blank=True)
    integrity_score = models.FloatField(null=True, blank=True)
    ai_recommendation = models.CharField(max_length=10, blank=True)
    total_distracted_seconds = models.FloatField(default=0)
    terminated = models.BooleanField(default=False)
    terminated_reason = models.CharField(max_length=200, blank=True)
    terminated_at = models.DateTimeField(null=True, blank=True)
    report = models.TextField(blank=True)
    video = models.FileField(upload_to="interview_videos/", blank=True, null=True)
    jsuser_id = models.IntegerField(null=True, blank=True)
    job_id = models.IntegerField(null=True, blank=True)
    synced_at = models.DateTimeField(null=True, blank=True)

    def __str__(self):
        return f"{self.candidate_name} ({self.status})"


class Question(models.Model):
    # old fields
    interview = models.ForeignKey(Interview, on_delete=models.CASCADE, related_name="questions")
    order = models.PositiveIntegerField(default=0)
    text = models.TextField()
    answer = models.TextField(blank=True)
    score = models.FloatField(null=True, blank=True)
    feedback = models.TextField(blank=True)
    typed_chars = models.PositiveIntegerField(default=0)
    voice_chars = models.PositiveIntegerField(default=0)
    paste_attempts = models.PositiveIntegerField(default=0)
    tab_switches = models.PositiveIntegerField(default=0)
    suspicious_input = models.BooleanField(default=False)

    # new fields
    asked_at = models.DateTimeField(null=True, blank=True)
    answered_at = models.DateTimeField(null=True, blank=True)
    time_taken_seconds = models.PositiveIntegerField(default=0)
    distracted_seconds = models.FloatField(default=0)
    distraction_count = models.PositiveIntegerField(default=0)

    class Meta:
        ordering = ["order"]


class ProctorEvent(models.Model):
    # old fields
    interview = models.ForeignKey(Interview, on_delete=models.CASCADE, related_name="events")
    message = models.CharField(max_length=300)
    created_at = models.DateTimeField(auto_now_add=True)

    # new field
    question = models.ForeignKey(
        Question, null=True, blank=True,
        on_delete=models.SET_NULL, related_name="events",
    )