# forms.py
from django import forms
from django.utils.safestring import mark_safe
from .models import Participant
import re
from django.core.exceptions import ValidationError

_DECIMAL_RE = re.compile(r"[^\d,\.]")

class ParticipantForm(forms.ModelForm):
    class Meta:
        model = Participant
        fields = [
            "group_name",
            "R_diff",
            "L_diff",
            "Ph_diff",
            "Pcu_diff",
            "s_vol_over_eta",
        ]
        widgets = {
            f: forms.NumberInput(attrs={"step": "0.1", "class": "input"})
            for f in fields if f != "group_name"
        }
        widgets["group_name"] = forms.TextInput(attrs={"class": "input"})
        labels = {
            "group_name": "Nombre del grupo",
            "R_diff": mark_safe("R<sub>diff</sub>"),
            "L_diff": mark_safe("L<sub>diff</sub>"),
            "Ph_diff": mark_safe("P<sub>h, diff</sub>"),
            "Pcu_diff": mark_safe("P<sub>cu, diff</sub>"),
            "s_vol_over_eta": mark_safe("S/Vol·η"),
        }
    def clean_s_vol_over_eta(self):
        raw = self.data.get("s_vol_over_eta", "")
        raw = _DECIMAL_RE.sub("", raw)   # quita letras o espacios
        raw = raw.replace(",", ".")      # coma → punto
        try:
            value = float(raw)
        except ValueError:
            raise ValidationError("Introduce un número válido (ej. 12.3)")
        if value <= 0:
            raise ValidationError("Debe ser mayor que 0")
        return value