from django.db import models
from django.conf import settings

class ApprovedScript(models.Model):
    """Scripts written by AI, approved by Owner, executed by Students."""
    title = models.CharField(max_length=200)
    description = models.TextField(blank=True)
    script_code = models.TextField(help_text="The exact Python/bash code to run")
    script_hash = models.CharField(max_length=64, help_text="SHA256 for integrity")
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)
    locked_until = models.DateTimeField(null=True, blank=True)
    active = models.BooleanField(default=True)
    order = models.PositiveIntegerField(default=0)

    def __str__(self):
        return self.title

class ScriptExecutionLog(models.Model):
    """Append-only log of every time a student clicks 'Run'."""
    script = models.ForeignKey(ApprovedScript, on_delete=models.CASCADE)
    executed_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    executed_at = models.DateTimeField(auto_now_add=True)
    status = models.CharField(max_length=20, choices=[("SUCCESS","Success"),("FAILED","Failed")])
    output_log = models.TextField(blank=True, help_text="Terminal output or error traceback")

    class Meta:
        ordering = ["-executed_at"]

    def __str__(self):
        return f"{self.script.title} - {self.status} - {self.executed_by}"
