
"""
AgencyType Model

This module contains the AgencyType model which represents different categories
of advertising agencies in the system. It provides a taxonomy for classifying
agencies based on their specialization, size, and service offerings.

Author: Senior Developer
Created: 2025-08-12
Version: 1.0

Dependencies:
    - Django 4.2+
    - django.utils.translation for internationalization
    - apps.common.models.BaseModel for shared functionality
"""


from django.db import models
from django.utils.translation import gettext_lazy as _
from django.core.validators import (
    FileExtensionValidator, 
    MinValueValidator, 
    MaxValueValidator,
    EmailValidator,
    URLValidator
)
from django.core.exceptions import ValidationError 
from django.utils import timezone 

from apps.accounts.models import User 
from apps.common.models import BaseModel, AddressModel

from apps.agencies.utils import agency_logo_upload_path



class AgencyType(BaseModel):
    """
        Model representing different types of advertising agencies.
        
        This model serves as a categorization system for agencies, allowing
        the platform to organize and filter agencies based on their specialization,
        size, and service offerings. It's designed to be flexible and extensible
        to accommodate various agency business models.
        
        Business Logic:
        - Agencies are categorized to help clients find the right type of agency
        - Premium types may have special features or higher visibility
        - Sort order allows for strategic positioning of agency types
        - Color coding enables consistent UI representation
        
        Relationships:
        - One AgencyType can have many Agencies (One-to-Many)
        - Uses PROTECT on delete to maintain referential integrity
        
        Attributes:
            name (CharField): The display name of the agency type
            description (TextField): Detailed description of the agency type
            color_code (CharField): Hex color code for UI representation
            sort_order (PositiveIntegerField): Display order priority
            is_premium (BooleanField): Premium type flag for special features
            
        Inherited from BaseModel:
            id (AutoField): Primary key
            created_at (DateTimeField): Record creation timestamp
            updated_at (DateTimeField): Last modification timestamp
            is_deleted (BooleanField): Soft delete flag
            
        Example Usage:
            # Create a new agency type
            agency_type = AgencyType.objects.create(
                name="Digital Marketing",
                description="Specialized in digital advertising and online marketing",
                color_code="#007bff",
                sort_order=1,
                is_premium=True
            )
            
            # Query premium agency types
            premium_types = AgencyType.objects.filter(is_premium=True)
            
            # Get agencies of a specific type
            digital_agencies = agency_type.agencies.filter(is_active=True)
    """
    
    # ========================================================================
    # FIELD DEFINITIONS
    # ========================================================================
    
    name = models.CharField(
        max_length=100,                    # Maximum length of 100 characters for agency type name
        unique=True,                       # Ensures no duplicate agency type names in the system
        verbose_name=_("Agency Type Name"), # Human-readable field name for admin interface
        help_text=_(                       # Help text displayed in forms and admin
            "The name of the agency type (e.g., Full Service, Digital, Creative). "
            "This name will be displayed throughout the platform and should be "
            "descriptive and professional."
        ),
        db_index=True                      # Creates database index for faster queries by name
    )
    
    description = models.TextField(
        blank=True,                        # Field is optional, can be left empty
        verbose_name=_("Description"),     # Human-readable field name
        help_text=_(                       # Detailed help text for users
            "Detailed description of what this agency type represents, "
            "including typical services, client types, and characteristics. "
            "This helps agencies and clients understand the category better."
        )
    )
    
    color_code = models.CharField(
        max_length=7,                      # Exactly 7 characters for hex color codes (#RRGGBB)
        default="#007bff",                 # Bootstrap primary blue as default color
        verbose_name=_("Color Code"),      # Human-readable field name
        help_text=_(                       # Instructions for color code format
            "Hex color code for UI representation (e.g., #007bff). "
            "This color will be used in charts, badges, and other UI elements "
            "to visually distinguish this agency type."
        ),
        db_index=True                      # Index for potential color-based filtering
    )
    
    sort_order = models.PositiveIntegerField(
        default=0,                         # Default sort order of 0 (highest priority)
        verbose_name=_("Sort Order"),      # Human-readable field name
        help_text=_(                       # Explanation of sort order behavior
            "Order in which agency types should be displayed. "
            "Lower numbers appear first. Use this to strategically "
            "position important agency types at the top of lists."
        ),
        db_index=True                      # Index for efficient ordering queries
    )
    
    is_premium = models.BooleanField(
        default=False,                     # Most agency types are not premium by default
        verbose_name=_("Premium Type"),    # Human-readable field name
        help_text=_(                       # Explanation of premium features
            "Whether this is a premium agency type with special features "
            "such as enhanced visibility, priority placement, or exclusive "
            "access to certain platform features."
        ),
        db_index=True                      # Index for filtering premium vs regular types
    )
    
    # ========================================================================
    # META CLASS CONFIGURATION
    # ========================================================================
    
    class Meta:
        """
        Meta class defining model behavior and database configuration.
        
        This configuration optimizes the model for performance and usability
        while ensuring proper internationalization and database structure.
        """
        
        verbose_name = _("Agency Type")           # Singular name for admin interface
        verbose_name_plural = _("Agency Types")  # Plural name for admin interface
        
        # Default ordering for QuerySets: sort_order ascending, then name ascending
        # This ensures premium/important types appear first, then alphabetical
        ordering = ['sort_order', 'name']
        
        # Custom database table name following Django naming conventions
        db_table = 'agencies_agency_type'
        
        # Additional database indexes for performance optimization
        indexes = [
            # Composite index for common filtering patterns
            models.Index(fields=['is_premium', 'sort_order'], name='idx_premium_sort'),
            
            # Index for active premium types (assuming BaseModel has is_deleted)
            models.Index(
                fields=['is_premium'], 
                condition=models.Q(is_deleted=False),
                name='idx_active_premium'
            ),
        ]
        
        # Database constraints for data integrity
        constraints = [
            # Ensure sort_order is non-negative
            models.CheckConstraint(
                check=models.Q(sort_order__gte=0),
                name='check_sort_order_positive'
            ),
            
            # Ensure color_code follows hex format (basic validation)
            models.CheckConstraint(
                check=models.Q(color_code__regex=r'^#[0-9A-Fa-f]{6}$'),
                name='check_color_code_format'
            ),
        ]
    
    # ========================================================================
    # INSTANCE METHODS
    # ========================================================================
    
    def __str__(self):
        """
        String representation of the agency type.
        
        Returns the name of the agency type, which is the most meaningful
        identifier for users and administrators.
        
        Returns:
            str: The name of the agency type
            
        Example:
            >>> agency_type = AgencyType(name="Digital Marketing")
            >>> str(agency_type)
            "Digital Marketing"
        """
        return self.name
    
    def __repr__(self):
        """
        Developer-friendly string representation.
        
        Provides detailed information about the instance for debugging
        and development purposes.
        
        Returns:
            str: Detailed representation including key attributes
        """
        return (
            f"<AgencyType(id={self.pk}, name='{self.name}', "
            f"premium={self.is_premium}, order={self.sort_order})>"
        )
    
    def clean(self):
        """
        Custom model validation logic.
        
        Performs validation that goes beyond simple field constraints,
        ensuring business rules are followed and data integrity is maintained.
        
        Raises:
            ValidationError: If validation fails
            
        Validation Rules:
        1. Name must not be empty or just whitespace
        2. Color code must be a valid hex color
        3. Description should not exceed reasonable length for display
        """
        super().clean()  # Call parent validation first
        
        # Validate and normalize the name field
        if self.name:
            # Remove leading/trailing whitespace
            self.name = self.name.strip()
            
            # Ensure name is not empty after stripping
            if not self.name:
                raise ValidationError({
                    'name': _("Agency type name cannot be empty or just whitespace.")
                })
            
            # Ensure name doesn't contain only special characters
            if not any(c.isalnum() for c in self.name):
                raise ValidationError({
                    'name': _("Agency type name must contain at least one letter or number.")
                })
        
        # Validate color code format (more comprehensive than constraint)
        if self.color_code:
            self.color_code = self.color_code.strip().upper()  # Normalize format
            
            # Check hex color format
            import re
            if not re.match(r'^#[0-9A-F]{6}$', self.color_code):
                raise ValidationError({
                    'color_code': _(
                        "Color code must be in hex format (e.g., #007BFF). "
                        "Use exactly 6 hexadecimal characters after the # symbol."
                    )
                })
        
        # Validate description length for practical display purposes
        if self.description and len(self.description) > 2000:
            raise ValidationError({
                'description': _(
                    "Description is too long. Please keep it under 2000 characters "
                    "for better display in user interfaces."
                )
            })
    
    def save(self, *args, **kwargs):
        """
        Custom save method with additional processing.
        
        Ensures validation is run and performs any necessary
        pre-save processing.
        
        Args:
            *args: Variable length argument list passed to parent save()
            **kwargs: Arbitrary keyword arguments passed to parent save()
        """
        # Run full model validation before saving
        self.full_clean()
        
        # Call parent save method
        super().save(*args, **kwargs)
    
    # ========================================================================
    # BUSINESS LOGIC METHODS
    # ========================================================================
    
    def get_agencies_count(self):
        """
        Get the total number of agencies of this type.
        
        Returns:
            int: Count of agencies associated with this type
            
        Example:
            >>> agency_type.get_agencies_count()
            15
        """
        return self.agencies.count()
    
    def get_active_agencies_count(self):
        """
        Get the number of active agencies of this type.
        
        Only counts agencies that are marked as active and not deleted.
        
        Returns:
            int: Count of active agencies of this type
            
        Example:
            >>> agency_type.get_active_agencies_count()
            12
        """
        return self.agencies.filter(is_active=True, is_deleted=False).count()
    
    def get_premium_agencies_count(self):
        """
        Get the number of premium agencies of this type.
        
        Counts agencies that are both active and marked as premium/featured.
        
        Returns:
            int: Count of premium agencies of this type
        """
        return self.agencies.filter(
            is_active=True, 
            is_deleted=False, 
            is_featured=True
        ).count()
    
    def is_popular(self, threshold=10):
        """
        Check if this agency type is popular based on agency count.
        
        Args:
            threshold (int): Minimum number of agencies to be considered popular
            
        Returns:
            bool: True if the agency type has at least threshold agencies
            
        Example:
            >>> agency_type.is_popular(threshold=5)
            True
        """
        return self.get_active_agencies_count() >= threshold
    
    def get_color_rgb(self):
        """
        Convert hex color code to RGB tuple.
        
        Returns:
            tuple: RGB values as (red, green, blue) integers (0-255)
            
        Example:
            >>> agency_type.color_code = "#007BFF"
            >>> agency_type.get_color_rgb()
            (0, 123, 255)
        """
        if not self.color_code or len(self.color_code) != 7:
            return (0, 123, 255)  # Default blue
        
        try:
            # Remove # and convert hex to RGB
            hex_color = self.color_code[1:]
            return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
        except ValueError:
            return (0, 123, 255)  # Fallback to default
    
    # ========================================================================
    # CLASS METHODS AND MANAGERS
    # ========================================================================
    
    @classmethod
    def get_default_types(cls):
        """
        Get a list of default agency types for system initialization.
        
        This is useful for data migration scripts or initial system setup.
        
        Returns:
            list: List of dictionaries with agency type data
            
        Example:
            >>> AgencyType.get_default_types()
            [{'name': 'Full Service', 'description': '...', ...}, ...]
        """
        return [
            {
                'name': _('Full Service'),
                'description': _('Comprehensive advertising services including strategy, creative, media, and digital'),
                'color_code': '#007BFF',
                'sort_order': 1,
                'is_premium': True
            },
            {
                'name': _('Digital Marketing'),
                'description': _('Specialized in digital advertising, social media, and online marketing'),
                'color_code': '#28A745',
                'sort_order': 2,
                'is_premium': True
            },
            {
                'name': _('Creative Agency'),
                'description': _('Focus on creative development, branding, and design services'),
                'color_code': '#DC3545',
                'sort_order': 3,
                'is_premium': False
            },
            {
                'name': _('Media Agency'),
                'description': _('Specialized in media planning, buying, and optimization'),
                'color_code': '#FFC107',
                'sort_order': 4,
                'is_premium': False
            },
            {
                'name': _('Boutique'),
                'description': _('Small, specialized agencies with niche expertise'),
                'color_code': '#6F42C1',
                'sort_order': 5,
                'is_premium': False
            }
        ]
    
    @classmethod
    def create_default_types(cls):
        """
        Create default agency types if they don't exist.
        
        This method is safe to run multiple times as it checks for
        existing types before creating new ones.
        
        Returns:
            list: List of created AgencyType instances
            
        Example:
            >>> created_types = AgencyType.create_default_types()
            >>> len(created_types)
            3  # Number of new types created
        """
        created_types = []
        
        for type_data in cls.get_default_types():
            # Check if type already exists
            existing_type = cls.objects.filter(name=type_data['name']).first()
            
            if not existing_type:
                # Create new type
                agency_type = cls.objects.create(**type_data)
                created_types.append(agency_type)
        
        return created_types


class Agency(BaseModel, AddressModel):
    """
    Model representing an advertising agency in the platform.
    
    This is the core model for agency management, containing all essential
    information about an advertising agency including business details,
    contact information, team structure, and operational settings.
    
    Business Logic:
    - Each agency has one owner who has full administrative rights
    - Agencies can have multiple team members with different roles
    - Agencies can manage multiple brands and their campaigns
    - Support for verification system to build trust
    - Premium features for enhanced visibility and functionality
    - Geographic information for location-based matching
    
    Relationships:
    - Belongs to one AgencyType (Many-to-One)
    - Owned by one User (Many-to-One)
    - Has many AgencyTeamMembers (One-to-Many)
    - Has many Brands (One-to-Many)
    - Has many Campaigns through Brands (One-to-Many-to-Many)
    
    Key Features:
    - Comprehensive business profile
    - Team management with role-based permissions
    - File upload handling for logos
    - Address management through AddressModel
    - Internationalization support
    - Performance optimization through indexing
    - Data validation and business rule enforcement
    
    Example Usage:
        # Create a new agency
        agency = Agency.objects.create(
            name="Creative Solutions Ltd",
            email="info@creativesolutions.com",
            agency_type=agency_type,
            owner=user,
            description="Full-service creative agency specializing in digital marketing"
        )
        
        # Check user permissions
        can_manage = agency.can_user_manage(user)
        
        # Get agency statistics
        brand_count = agency.get_active_brands_count()
        campaign_count = agency.get_active_campaigns_count()
    """
    
    # ========================================================================
    # CHOICE FIELD DEFINITIONS
    # ========================================================================
    
    AGENCY_SIZE_CHOICES = [
        # Each tuple contains (database_value, display_label)
        ('startup', _('Startup (1-10 employees)')),      # Small startups and solo agencies
        ('small', _('Small (11-50 employees)')),         # Small to medium agencies
        ('medium', _('Medium (51-200 employees)')),      # Mid-size agencies
        ('large', _('Large (201-1000 employees)')),      # Large agencies with multiple departments
        ('enterprise', _('Enterprise (1000+ employees)')), # Global agency networks
    ]
    
    SPECIALIZATION_CHOICES = [
        # Core advertising and marketing specializations
        ('tv_advertising', _('TV Advertising')),         # Traditional television advertising
        ('digital_marketing', _('Digital Marketing')),   # Online marketing and advertising
        ('creative_services', _('Creative Services')),   # Design, copywriting, creative development
        ('media_planning', _('Media Planning')),         # Media strategy and buying
        ('brand_strategy', _('Brand Strategy')),         # Brand development and positioning
        ('public_relations', _('Public Relations')),    # PR and communications
        ('social_media', _('Social Media')),            # Social media marketing and management
        ('content_creation', _('Content Creation')),    # Video, photo, and content production
        ('data_analytics', _('Data Analytics')),        # Marketing analytics and insights
        ('full_service', _('Full Service')),            # Comprehensive agency services
    ]
    
    # ========================================================================
    # BASIC INFORMATION FIELDS
    # ========================================================================
    
    name = models.CharField(
        max_length=200,                          # Maximum 200 characters for agency name
        verbose_name=_("Agency Name"),           # Human-readable field label
        help_text=_(                             # Detailed help text for forms
            "The display name of the advertising agency as it appears "
            "to clients and in public listings. This should be the "
            "official business name or commonly used trading name."
        ),
        db_index=True                            # Database index for fast name-based searches
    )
    
    legal_name = models.CharField(
        max_length=200,                          # Same length as name for consistency
        blank=True,                              # Optional field - not all agencies need this
        verbose_name=_("Legal Name"),            # Human-readable field label
        help_text=_(                             # Explanation of when to use this field
            "The legal business name of the agency if different from the "
            "display name. Used for contracts, invoicing, and legal documents."
        )
    )
    
    agency_type = models.ForeignKey(
        'agencies.AgencyType',                   # Reference to AgencyType model (string to avoid circular import)
        on_delete=models.PROTECT,                # Prevent deletion of referenced AgencyType
        related_name='agencies',                 # Reverse relationship name for AgencyType.agencies
        verbose_name=_("Agency Type"),           # Human-readable field label
        help_text=_(                             # Explanation of agency type purpose
            "The type/category of this agency (e.g., Full Service, Digital, "
            "Creative). This helps in categorizing and filtering agencies."
        ),
        db_index=True                            # Index for filtering by agency type
    )
    
    description = models.TextField(
        blank=True,                              # Optional field for agencies without descriptions
        verbose_name=_("Description"),           # Human-readable field label
        help_text=_(                             # Guidelines for description content
            "Detailed description of the agency and its services. This appears "
            "in agency profiles and helps clients understand what the agency offers. "
            "Include key services, specializations, and unique value propositions."
        )
    )
    
    logo = models.ImageField(
        upload_to=agency_logo_upload_path,       # Custom function to determine upload directory
        blank=True,                              # Optional - agencies can operate without logos
        null=True,                               # Allow NULL in database
        verbose_name=_("Logo"),                  # Human-readable field label
        help_text=_(                             # File upload guidelines
            "Agency logo image. Recommended size: 300x300 pixels or larger. "
            "Accepted formats: JPG, PNG, SVG, WebP. Maximum file size: 5MB."
        ),
        validators=[                             # File validation rules
            FileExtensionValidator(
                allowed_extensions=['jpg', 'jpeg', 'png', 'svg', 'webp']
            )
        ]
    )
    
    # ========================================================================
    # CONTACT INFORMATION FIELDS
    # ========================================================================
    
    website = models.URLField(
        blank=True,                              # Optional field - not all agencies have websites
        verbose_name=_("Website"),               # Human-readable field label
        help_text=_(                             # URL format guidelines
            "Agency website URL including http:// or https://. "
            "This link will be displayed in agency profiles."
        ),
        validators=[URLValidator()]              # Validates URL format
    )
    
    phone = models.CharField(
        max_length=20,                           # Supports international phone formats
        blank=True,                              # Optional contact method
        verbose_name=_("Phone Number"),          # Human-readable field label
        help_text=_(                             # Phone format guidelines
            "Primary phone number including country code if international. "
            "Example formats: +1-555-123-4567, (555) 123-4567, +44 20 7123 4567"
        )
    )
    
    email = models.EmailField(
        verbose_name=_("Email Address"),         # Human-readable field label
        help_text=_(                             # Email usage explanation
            "Primary email address for the agency. This will be used for "
            "platform communications and displayed in agency profiles."
        ),
        validators=[EmailValidator()],           # Validates email format
        db_index=True                            # Index for email-based lookups
    )
    
    # ========================================================================
    # BUSINESS INFORMATION FIELDS
    # ========================================================================
    
    founded_year = models.PositiveIntegerField(
        blank=True,                              # Optional historical information
        null=True,                               # Allow NULL in database
        validators=[                             # Reasonable year range validation
            MinValueValidator(1900),             # Agencies founded after 1900
            MaxValueValidator(2030)              # Future-proof until 2030
        ],
        verbose_name=_("Founded Year"),          # Human-readable field label
        help_text=_(                             # Year format explanation
            "The year the agency was founded. Used to calculate agency "
            "experience and for historical context in profiles."
        ),
        db_index=True                            # Index for experience-based filtering
    )
    
    agency_size = models.CharField(
        max_length=20,                           # Sufficient for choice values
        choices=AGENCY_SIZE_CHOICES,             # Predefined size categories
        default='small',                         # Most agencies start small
        verbose_name=_("Agency Size"),           # Human-readable field label
        help_text=_(                             # Size category explanation
            "Size category based on employee count. This helps clients "
            "understand the agency's capacity and structure."
        ),
        db_index=True                            # Index for size-based filtering
    )
    
    employee_count = models.PositiveIntegerField(
        blank=True,                              # Optional - size category may be sufficient
        null=True,                               # Allow NULL in database
        verbose_name=_("Employee Count"),        # Human-readable field label
        help_text=_(                             # Employee count guidelines
            "Exact number of employees in the agency. This provides more "
            "precise information than the size category alone."
        )
    )
    
    specializations = models.JSONField(
        default=list,                            # Default to empty list
        blank=True,                              # Optional field
        verbose_name=_("Specializations"),       # Human-readable field label
        help_text=_(                             # Specialization usage explanation
            "List of agency specializations and service areas. "
            "Use this to highlight key competencies and expertise areas."
        )
    )
    
    # ========================================================================
    # STATUS AND FEATURE FLAGS
    # ========================================================================
    
    is_verified = models.BooleanField(
        default=False,                           # Agencies start unverified
        verbose_name=_("Verified"),              # Human-readable field label
        help_text=_(                             # Verification explanation
            "Whether the agency has been verified by platform administrators. "
            "Verified agencies have enhanced credibility and may receive "
            "preferential placement in search results."
        ),
        db_index=True                            # Index for filtering verified agencies
    )
    
    is_featured = models.BooleanField(
        default=False,                           # Most agencies are not featured
        verbose_name=_("Featured"),              # Human-readable field label
        help_text=_(                             # Featured status explanation
            "Whether to feature this agency in listings and search results. "
            "Featured agencies receive enhanced visibility and premium placement."
        ),
        db_index=True                            # Index for featured agency queries
    )
    
    is_active = models.BooleanField(
        default=True,                            # Agencies are active by default
        verbose_name=_("Active"),                # Human-readable field label
        help_text=_(                             # Active status explanation
            "Whether the agency is currently active on the platform. "
            "Inactive agencies are hidden from public listings but data is preserved."
        ),
        db_index=True                            # Index for active agency filtering
    )
    
    # ========================================================================
    # LOCALIZATION AND PREFERENCES
    # ========================================================================
    
    time_zone = models.CharField(
        max_length=50,                           # Supports all timezone identifiers
        default='UTC',                           # Universal default timezone
        verbose_name=_("Time Zone"),             # Human-readable field label
        help_text=_(                             # Timezone usage explanation
            "Primary time zone for the agency. Used for scheduling, "
            "campaign timing, and communication preferences."
        )
    )
    
    language = models.CharField(
        max_length=10,                           # ISO 639-1 language codes (2-5 chars typically)
        default='en',                            # English as default language
        verbose_name=_("Language"),              # Human-readable field label
        help_text=_(                             # Language code explanation
            "Primary language preference using ISO 639-1 code "
            "(e.g., 'en' for English, 'es' for Spanish, 'fr' for French)."
        )
    )
    
    # ========================================================================
    # RELATIONSHIP FIELDS
    # ========================================================================
    
    owner = models.ForeignKey(
        User,                                    # Reference to User model
        on_delete=models.CASCADE,                # Delete agency if owner is deleted
        related_name='owned_agencies',           # Reverse relationship name for User.owned_agencies
        verbose_name=_("Owner"),                 # Human-readable field label
        help_text=_(                             # Owner role explanation
            "Primary owner of the agency with full administrative rights. "
            "The owner can manage all aspects of the agency including "
            "team members, brands, and campaigns."
        ),
        db_index=True                            # Index for owner-based queries
    )

    class Meta: 
        verbose_name = _("Agency")
        verbose_name_plural = _("Agencies")
        ordering = ['-is_featured', '-is_verified', 'name']
        db_table = 'Agency'
        indexes = [
            models.Index(fields=['name']),
            models.Index(fields=['agency_type']),
            models.Index(fields=['is_verified', 'is_active']),
            models.Index(fields=['is_featured', 'is_active']),
        ]

    def __str__(self):
        """Return string representation of the agency."""
        return self.name
    
    def get_full_address(self):
        """
        Get the complete formatted address of the agency.
        
        Returns:
            str: Formatted address string
        """
        address_parts = []
        if self.street_address:
            address_parts.append(self.street_address)
        if self.city:
            address_parts.append(self.city)
        if self.state_province:
            address_parts.append(self.state_province)
        if self.postal_code:
            address_parts.append(self.postal_code)
        if self.country:
            address_parts.append(self.country)
        
        return ', '.join(address_parts)
    
    def get_employee_count_display(self):
        """
        Get a human-readable display of employee count.
        
        Returns:
            str: Employee count range or exact number
        """
        if self.employee_count:
            return str(self.employee_count)
        return dict(self.AGENCY_SIZE_CHOICES).get(self.agency_size, 'Unknown')
    
    @property
    def is_premium(self):
        """Check if the agency is of a premium type."""
        return self.agency_type.is_premium if self.agency_type else False
    
    @property
    def founded_year_str(self):
        """Return founded year as string without comma formatting."""
        return str(self.founded_year) if self.founded_year else None



class AgencyTeamMember(BaseModel):
    """
    Model representing team members within agencies.
    
    This model tracks the team members of agencies, their roles,
    and contact information for client relationship management.
    
    Attributes:
        agency (Agency): The agency this person works for
        user (User): Associated user account (if any)
 
        position (str): Job title/position
        department (str): Department within the agency
  
        is_primary_contact (bool): Whether this is the primary contact
        is_public (bool): Whether to show in public listings
        linkedin_url (str): LinkedIn profile URL
        years_experience (int): Years of experience
        specializations (JSONField): Areas of expertise
    """
    
    # Department Choices
    DEPARTMENT_CHOICES = [
        ('management', _('Management')),
        ('account', _('Account Management')),
        ('creative', _('Creative')),
        ('strategy', _('Strategy')),
        ('media', _('Media')),
        ('production', _('Production')),
        ('digital', _('Digital')),
        ('analytics', _('Analytics')),
        ('finance', _('Finance')),
        ('hr', _('Human Resources')),
        ('other', _('Other')),
    ]
    
    agency = models.ForeignKey(
        Agency,
        on_delete=models.CASCADE,
        related_name='team_members',
        verbose_name=_("Agency"),
        help_text=_("The agency this person works for")
    )
    
    user = models.ForeignKey(
        User,
        on_delete=models.SET_NULL,
        blank=True,
        null=True,
        related_name='agency_memberships',
        verbose_name=_("User Account"),
        help_text=_("Associated user account (if any)")
    ) 
     
    
    department = models.CharField(
        max_length=20,
        choices=DEPARTMENT_CHOICES,
        default='other',
        verbose_name=_("Department"),
        help_text=_("Department within the agency")
    ) 
    
    is_primary_contact = models.BooleanField(
        default=False,
        verbose_name=_("Primary Contact"),
        help_text=_("Whether this person is the primary contact for the agency")
    )
    
    is_public = models.BooleanField(
        default=True,
        verbose_name=_("Public Profile"),
        help_text=_("Whether to show this person in public agency listings")
    ) 
    
    years_experience = models.PositiveIntegerField(
        blank=True,
        null=True,
        verbose_name=_("Years of Experience"),
        help_text=_("Total years of professional experience")
    )
    
    specializations = models.JSONField(
        default=list,
        blank=True,
        verbose_name=_("Specializations"),
        help_text=_("Areas of expertise and specialization")
    )
    
    class Meta:
        verbose_name = _("Agency Team Member")
        verbose_name_plural = _("Agency Team Members")
        ordering = ['-is_primary_contact', 'user__last_name', 'user__first_name']
        db_table = 'agencies_team_member' 
    
    def __str__(self):
        """Return string representation of the team member."""
        return f"{self.first_name} {self.last_name} - {self.agency.name}"
    
    @property
    def full_name(self):
        """Get the full name of the team member."""
        return self.user.get_full_name()

