from __future__ import annotations

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

from apps.core.ids import uuid7
from apps.core.models import BaseModel, UUIDModel


class EquipmentCategory(UUIDModel):
    code = models.CharField(max_length=32, unique=True)
    name_fr = models.CharField(max_length=120)
    maintenance_interval_days = models.PositiveIntegerField(null=True, blank=True)

    class Meta:
        verbose_name = "catégorie d'équipement"

    def __str__(self):
        return self.name_fr


class Equipment(BaseModel):
    class Status(models.TextChoices):
        IN_SERVICE = "IN_SERVICE", "En service"
        UNDER_MAINTENANCE = "UNDER_MAINTENANCE", "En maintenance"
        BROKEN = "BROKEN", "En panne"
        OUT_OF_SERVICE = "OUT_OF_SERVICE", "Hors service"
        DECOMMISSIONED = "DECOMMISSIONED", "Réformé"

    inventory_number = models.CharField(max_length=40, unique=True)
    agency = models.ForeignKey("agencies.Agency", on_delete=models.CASCADE, related_name="equipment")
    category = models.ForeignKey(EquipmentCategory, on_delete=models.PROTECT, related_name="equipment")
    name = models.CharField(max_length=160)
    brand = models.CharField(max_length=80, blank=True)
    model = models.CharField(max_length=80, blank=True)
    serial_number = models.CharField(max_length=80, blank=True)
    purchase_date = models.DateField(null=True, blank=True)
    purchase_value_xaf = models.BigIntegerField(default=0)
    location = models.CharField(max_length=120, blank=True)
    status = models.CharField(max_length=20, choices=Status.choices, default=Status.IN_SERVICE)
    warranty_end = models.DateField(null=True, blank=True)
    next_maintenance_on = models.DateField(null=True, blank=True)
    usage_hours = models.PositiveIntegerField(default=0)
    notes = models.TextField(blank=True)
    photo = models.ImageField(upload_to="equipment/", blank=True, null=True)

    class Meta:
        verbose_name = "équipement"
        ordering = ["name"]
        indexes = [models.Index(fields=["agency", "status"]), models.Index(fields=["next_maintenance_on"])]
        permissions = [
            ("report_incident", "Peut déclarer une panne"),
            ("manage_maintenance", "Peut gérer la maintenance"),
            ("transfer_equipment", "Peut transférer un équipement"),
            ("export_equipment", "Peut exporter les équipements"),
        ]

    def __str__(self):
        return f"{self.inventory_number} — {self.name}"

    @property
    def is_available(self):
        return self.status == self.Status.IN_SERVICE

    @property
    def open_incidents(self):
        return self.incidents.exclude(status__in=["RESOLVED", "CLOSED"]).count()

    @property
    def maintenance_overdue(self):
        return bool(self.next_maintenance_on and self.next_maintenance_on < timezone.localdate())


class Incident(UUIDModel):
    code = models.CharField(max_length=40, unique=True)
    equipment = models.ForeignKey(Equipment, on_delete=models.CASCADE, related_name="incidents")
    severity = models.CharField(max_length=10, choices=[("LOW", "Faible"), ("MEDIUM", "Moyenne"), ("HIGH", "Haute"), ("CRITICAL", "Critique")], default="MEDIUM")
    description = models.TextField()
    reported_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL, related_name="+")
    reported_at = models.DateTimeField(default=timezone.now)
    status = models.CharField(max_length=12, default="OPEN", choices=[("OPEN", "Ouvert"), ("IN_PROGRESS", "En cours"), ("RESOLVED", "Résolu"), ("CLOSED", "Clôturé")])
    resolved_at = models.DateTimeField(null=True, blank=True)
    resolution = models.TextField(blank=True)

    class Meta:
        verbose_name = "incident"
        ordering = ["-reported_at"]


class MaintenanceIntervention(UUIDModel):
    equipment = models.ForeignKey(Equipment, on_delete=models.CASCADE, related_name="interventions")
    incident = models.ForeignKey(Incident, null=True, blank=True, on_delete=models.SET_NULL, related_name="interventions")
    intervention_type = models.CharField(max_length=12, choices=[("PREVENTIVE", "Préventive"), ("CORRECTIVE", "Corrective")], default="CORRECTIVE")
    scheduled_on = models.DateField(null=True, blank=True)
    done_on = models.DateField(null=True, blank=True)
    technician = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL, related_name="+")
    diagnosis = models.TextField(blank=True)
    actions = models.TextField(blank=True)
    cost_xaf = models.BigIntegerField(default=0)
    status = models.CharField(max_length=12, default="PLANNED", choices=[("PLANNED", "Planifiée"), ("DONE", "Réalisée"), ("CANCELLED", "Annulée")])

    class Meta:
        verbose_name = "intervention de maintenance"
        ordering = ["-scheduled_on"]
