from pydantic import BaseModel, EmailStr, Field, field_validator
from typing import Optional
from datetime import date, datetime
from decimal import Decimal
from app.utils.validation_helpers import clean_phone, clean_fein
import re

class GroupLifeBase(BaseModel):
    company_name: str = Field(..., max_length=100)
    industry_type: str = Field(..., max_length=100)
    federal_tax_id: str = Field(..., max_length=255)
    company_address: str = Field(..., max_length=500)
    
    contact_name: str = Field(..., max_length=100)
    contact_email: EmailStr
    contact_phone: str = Field(..., max_length=15)
    
    type_of_group: str = Field(..., max_length=50)
    number_of_eligible_employees: int = Field(..., ge=2)
    number_of_employees_to_be_insured: int = Field(..., ge=1)
    employee_locations: str = Field(..., max_length=1000)
    
    coverage_type_requested: str = Field(..., max_length=500)
    requested_effective_date: date
    
    current_group_life_carrier: Optional[str] = Field(None, max_length=255)
    current_monthly_premium: Optional[Decimal] = Field(None, decimal_places=2)
    current_benefit_design: Optional[str] = Field(None, max_length=1000)
    desired_benefit_design: Optional[str] = Field(None, max_length=1000)
    
    employer_contribution_percentage: Optional[float] = Field(None, ge=0, le=100)
    waiting_period_eligibility: str = Field(..., max_length=255)
    class_structure: Optional[str] = Field(None, max_length=1000)
    union_non_union_mix: Optional[str] = Field(None, max_length=20)
    renewal_month: Optional[str] = Field(None, max_length=20)
    
    broker_consultant_name: Optional[str] = Field(None, max_length=255)
    additional_notes: Optional[str] = Field(None, max_length=1000)
    employee_census_file_path: Optional[str] = Field(None, max_length=500)
    transaction_no: str

    @field_validator('federal_tax_id', mode='before')
    @classmethod
    def validate_federal_tax_id(cls, v):
        if v:
            clean_id = clean_fein(v)
            if not re.match(r'^\d{9}$', clean_id):
                raise ValueError('Federal Tax ID must be 9-digit numeric')
            return clean_id
        return v

    @field_validator('contact_phone', mode='before')
    @classmethod
    def validate_contact_phone(cls, v):
        if v:
            v = clean_phone(v)
            if not re.match(r'^\(\d{3}\) \d{3}-\d{4}$', v):
                raise ValueError('Phone number must be in format (XXX) XXX-XXXX')
        return v

    @field_validator('requested_effective_date')
    @classmethod
    def validate_future_date(cls, v):
        if v <= date.today():
            raise ValueError('Requested effective date must be a future date')
        return v

    @field_validator('number_of_employees_to_be_insured')
    @classmethod
    def validate_insured_employees(cls, v, values):
        if 'number_of_eligible_employees' in values.data and v > values.data['number_of_eligible_employees']:
            raise ValueError('Employees to be insured cannot exceed eligible employees')
        return v

class GroupLifeCreate(GroupLifeBase):
    pass

class GroupLifeUpdate(BaseModel):
    company_name: Optional[str] = Field(None, max_length=100)
    industry_type: Optional[str] = Field(None, max_length=100)
    federal_tax_id: Optional[str] = Field(None, max_length=255)
    company_address: Optional[str] = Field(None, max_length=500)
    
    contact_name: Optional[str] = Field(None, max_length=100)
    contact_email: Optional[EmailStr] = None
    contact_phone: Optional[str] = Field(None, max_length=15)
    
    type_of_group: Optional[str] = Field(None, max_length=50)
    number_of_eligible_employees: Optional[int] = Field(None, ge=2)
    number_of_employees_to_be_insured: Optional[int] = Field(None, ge=1)
    employee_locations: Optional[str] = Field(None, max_length=1000)
    
    coverage_type_requested: Optional[str] = Field(None, max_length=500)
    requested_effective_date: Optional[date] = None
    
    current_group_life_carrier: Optional[str] = Field(None, max_length=255)
    current_monthly_premium: Optional[Decimal] = Field(None, decimal_places=2)
    current_benefit_design: Optional[str] = Field(None, max_length=1000)
    desired_benefit_design: Optional[str] = Field(None, max_length=1000)
    
    employer_contribution_percentage: Optional[float] = Field(None, ge=0, le=100)
    waiting_period_eligibility: Optional[str] = Field(None, max_length=255)
    class_structure: Optional[str] = Field(None, max_length=1000)
    union_non_union_mix: Optional[str] = Field(None, max_length=20)
    renewal_month: Optional[str] = Field(None, max_length=20)
    
    broker_consultant_name: Optional[str] = Field(None, max_length=255)
    additional_notes: Optional[str] = Field(None, max_length=1000)
    employee_census_file_path: Optional[str] = Field(None, max_length=500)
    
    quote_status: Optional[str] = Field(None, max_length=50)
    premium_amount: Optional[Decimal] = Field(None, decimal_places=2)

class GroupLifeResponse(GroupLifeBase):
    id: int
    quote_status: str
    premium_amount: Optional[Decimal]
    created_at: datetime
    updated_at: Optional[datetime]
    
    class Config:
        from_attributes = True