from django import forms
from .models import ScanProfile

_INPUT = (
    'w-full border border-gray-300 rounded-lg px-3 py-2 text-sm text-gray-700 '
    'focus:outline-none focus:ring-2 focus:ring-red-500 focus:border-transparent'
)
_TEXTAREA = _INPUT + ' resize-none'


class ScanProfileForm(forms.ModelForm):
    domains_text = forms.CharField(
        widget=forms.Textarea(attrs={
            'rows': 4,
            'placeholder': 'to.junv.cc\ngo.junv.cc',
            'class': _TEXTAREA,
        }),
        required=False,
        label='Domains (one per line)',
        help_text='Public hostnames to check for TLS and auth.',
    )
    cameras_text = forms.CharField(
        widget=forms.Textarea(attrs={
            'rows': 3,
            'placeholder': '192.168.1.70\n192.168.1.71',
            'class': _TEXTAREA,
        }),
        required=False,
        label='Camera IPs (one per line)',
        help_text='Local IP addresses of cameras to probe for unauthenticated RTSP.',
    )

    class Meta:
        model = ScanProfile
        fields = [
            'name', 'enabled', 'schedule_interval',
            'gateway_ip', 'public_ip', 'network_cidr',
            'auth_provider_host',
            'telegram_bot_token', 'telegram_chat_id', 'notify_on_severity',
        ]
        widgets = {
            'name': forms.TextInput(attrs={'class': _INPUT}),
            'schedule_interval': forms.Select(attrs={'class': _INPUT}),
            'gateway_ip': forms.TextInput(attrs={'class': _INPUT}),
            'public_ip': forms.TextInput(attrs={'class': _INPUT}),
            'network_cidr': forms.TextInput(attrs={'class': _INPUT}),
            'auth_provider_host': forms.TextInput(attrs={'class': _INPUT}),
            'telegram_bot_token': forms.PasswordInput(render_value=True, attrs={'class': _INPUT}),
            'telegram_chat_id': forms.TextInput(attrs={'class': _INPUT}),
            'notify_on_severity': forms.Select(attrs={'class': _INPUT}),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.instance and self.instance.pk:
            self.fields['domains_text'].initial = '\n'.join(self.instance.domains or [])
            self.fields['cameras_text'].initial = '\n'.join(self.instance.cameras or [])

    def clean_domains_text(self):
        raw = self.cleaned_data.get('domains_text', '')
        return [line.strip() for line in raw.splitlines() if line.strip()]

    def clean_cameras_text(self):
        raw = self.cleaned_data.get('cameras_text', '')
        return [line.strip() for line in raw.splitlines() if line.strip()]

    def save(self, commit=True):
        instance = super().save(commit=False)
        instance.domains = self.cleaned_data['domains_text']
        instance.cameras = self.cleaned_data['cameras_text']
        if commit:
            instance.save()
        return instance
