from django import forms
from plans.models import Plan


class AddDomainForm(forms.Form):
    name = forms.CharField(label='主域名', max_length=253)
    subdomains = forms.CharField(label='接入子域名（逗号分隔）', required=False, help_text='例如：www,static')
    origin_host = forms.CharField(label='源站地址（域名或IP）', max_length=253)
    origin_protocol = forms.ChoiceField(label='回源协议', choices=[('http', 'HTTP'), ('https', 'HTTPS')], initial='http')
    origin_port = forms.IntegerField(label='回源端口', initial=80, min_value=1, max_value=65535)
    plan = forms.ModelChoiceField(
        label='套餐',
        queryset=Plan.objects.filter(is_active=True, is_public=True, allow_new_purchase=True),
        required=False
    )
    enable_websocket = forms.BooleanField(label='启用WebSocket', required=False, initial=False)

    def clean(self):
        cleaned = super().clean()
        # 规范化子域名列表
        subs_raw = cleaned.get('subdomains') or ''
        subs = [s.strip() for s in subs_raw.split(',') if s.strip()]
        cleaned['subdomains'] = subs
        return cleaned


class DomainSettingsForm(forms.Form):
    waf_enabled = forms.BooleanField(label='启用 WAF', required=False)
    http3_enabled = forms.BooleanField(label='启用 HTTP/3', required=False)
    logs_enabled = forms.BooleanField(label='启用实时日志', required=False)
    websocket_enabled = forms.BooleanField(label='启用 WebSocket', required=False)
    redirect_https_enabled = forms.BooleanField(label='强制 HTTP→HTTPS 跳转', required=False)
    cache_rules_json = forms.CharField(label='缓存规则（JSON）', required=False, widget=forms.Textarea(attrs={'rows': 6}))
    ip_whitelist = forms.CharField(label='IP 白名单（逗号分隔）', required=False, widget=forms.Textarea(attrs={'rows': 3}))
    ip_blacklist = forms.CharField(label='IP 黑名单（逗号分隔）', required=False, widget=forms.Textarea(attrs={'rows': 3}))
    page_rules_json = forms.CharField(label='页面规则（JSON）', required=False, widget=forms.Textarea(attrs={'rows': 6}))

    def clean_cache_rules_json(self):
        val = self.cleaned_data.get('cache_rules_json') or ''
        if not val.strip():
            return {}
        import json
        try:
            return json.loads(val)
        except Exception:
            raise forms.ValidationError('缓存规则需为合法 JSON')

    def clean_page_rules_json(self):
        val = self.cleaned_data.get('page_rules_json') or ''
        if not val.strip():
            return {}
        import json
        try:
            return json.loads(val)
        except Exception:
            raise forms.ValidationError('页面规则需为合法 JSON')

    def clean_ip_whitelist(self):
        val = self.cleaned_data.get('ip_whitelist') or ''
        ips = [s.strip() for s in val.split(',') if s.strip()]
        return ips

    def clean_ip_blacklist(self):
        val = self.cleaned_data.get('ip_blacklist') or ''
        ips = [s.strip() for s in val.split(',') if s.strip()]
        return ips