from django.contrib.auth import get_user_model
from django.db import models
from django.utils import timezone

import uuid

User = get_user_model()


def submission_file_upload_path(instance, filename):
    """Generate upload path for submission files"""
    # Create path: submissions/{submission_id}/{uuid}_{filename}
    ext = filename.split(".")[-1] if "." in filename else ""
    new_filename = f"{uuid.uuid4()}_{filename}" if ext else str(uuid.uuid4())
    return f"noita-submissions/{instance.id}/{new_filename}"


class LogfileSubmission(models.Model):
    """Model representing a submission containing multiple puzzle responses"""

    # Identification
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

    content_type = models.CharField(max_length=100, help_text="MIME type of the file")
    file_size = models.PositiveIntegerField(help_text="File size in bytes")
    file = models.FileField(
        upload_to=submission_file_upload_path,
        help_text="Uploaded file (image/gif)",
    )

    # User information (optional for anonymous submissions)
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        help_text="User who made the submission (null for anonymous)",
        related_name="noita_submissions",
    )

    # Timestamps
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    processed = models.BooleanField(default=False)


class Objectiv(models.Model):
    objectiv_id = models.CharField(max_length=64)

    user = models.ForeignKey(User, on_delete=models.CASCADE)

    first_seen_at = models.DateTimeField(default=timezone.now)
    seed = models.CharField(max_length=32)
    submission = models.ForeignKey("LogfileSubmission", on_delete=models.CASCADE)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=["objectiv_id", "user", "first_seen_at"],
                name="unique_objectiv_per_user_timestamp",
            )
        ]


class ObjectivPoint(models.Model):
    objectiv_id = models.CharField(max_length=64, unique=True)
    display_string = models.CharField(max_length=255)
    max_count = models.IntegerField(default=1)
    point = models.IntegerField(default=0)


class DeathCounter(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    seed = models.CharField(max_length=32)
    seen_at = models.DateTimeField()

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=["user_id", "seen_at"],
                name="unique_death_per_seen_at",
            )
        ]
