from django import forms
from .models import Organization

class OrganizationForm(forms.ModelForm):
    class Meta:
        model = Organization
        fields = [
            'name', 'email', 'employee_headcount', 'annual_revenue', 'critical_applications',
            'compliance_frameworks', 'industry_sector', 'it_dependency', 'data_sensitivity',
            'network_infrastructure', 'remote_workforce_percentage', 'third_party_vendor_access',
            'internal_software_development', 'geographic_scope', 'customer_base', 'customer_type',
            'product_portfolio', 'supplier_base', 'it_infrastructure', 'intellectual_property',
            'sensitive_data','sensitive_data_types', 'integration_level', 'ip_value', 'change_rate', 'threat_actors'
        ]
        widgets = {
            'compliance_frameworks': forms.CheckboxSelectMultiple(),
            'it_infrastructure': forms.CheckboxSelectMultiple(),
            'intellectual_property': forms.CheckboxSelectMultiple(),
            'sensitive_data': forms.CheckboxSelectMultiple(),
            'threat_actors': forms.CheckboxSelectMultiple(),
            'sensitive_data_types': forms.CheckboxSelectMultiple(),
        }

    def clean(self):
        cleaned_data = super().clean()

        # Handle compliance_frameworks "Other"
        frameworks = cleaned_data.get('compliance_frameworks', [])
        other_framework = self.data.get('compliance_frameworks_other', '').strip()
        if 'other' in frameworks and other_framework:
            frameworks = [fw for fw in frameworks if fw != 'other']
            frameworks.append(other_framework)
        cleaned_data['compliance_frameworks'] = frameworks

        # Handle industry_sector "Other"
        sector = cleaned_data.get('industry_sector')
        sector_other = self.data.get('industry_sector_other', '').strip()
        if sector == 'other' and sector_other:
            cleaned_data['industry_sector'] = sector_other

        # Handle sensitive_data_types
        types = cleaned_data.get('sensitive_data_types') or []
        other_type = self.data.get('sensitive_data_types_other', '').strip()
        if 'other' in types and other_type:
            types = [t for t in types if t != 'other']
            types.append(other_type)
        cleaned_data['sensitive_data_types'] = types

        return cleaned_data
