from pydantic import BaseModel, EmailStr, Field, field_validator
from typing import Optional
from datetime import date, datetime
from decimal import Decimal
import re

from app.utils.validation_helpers import clean_phone, clean_state, clean_fein

class GroupHealthBase(BaseModel):
    company_name: str = Field(..., min_length=2, max_length=100)
    industry_sic_code: str = Field(..., max_length=10)
    company_address: str = Field(..., max_length=500)
    city: str = Field(..., max_length=100)
    state: str = Field(..., max_length=2)
    zip_code: str = Field(..., max_length=10)
    federal_tax_id: Optional[str] = Field(None, max_length=9)
    
    number_of_employees: int = Field(..., ge=1)
    number_of_employees_to_be_covered: int = Field(..., ge=1)
    average_age_of_employees: Optional[float] = Field(None, ge=18, le=100)
    employee_census_file_path: Optional[str] = Field(None, max_length=500)
    
    type_of_coverage_requested: str = Field(..., max_length=500)
    desired_coverage_start_date: date
    
    current_insurance_carrier: Optional[str] = Field(None, max_length=255)
    current_plan_type: Optional[str] = Field(None, max_length=50)
    monthly_premium_current_plan: Optional[Decimal] = Field(None, decimal_places=2)
    
    contribution_strategy: Optional[str] = Field(None, max_length=50)
    waiting_period_new_employees: Optional[str] = Field(None, max_length=20)
    
    broker_agent_involved: bool
    broker_agent_name: Optional[str] = Field(None, max_length=255)
    
    contact_person_name: str = Field(..., max_length=255)
    contact_email: EmailStr
    contact_phone: str = Field(..., max_length=15)
    preferred_contact_method: Optional[str] = Field(None, max_length=20)
    notes_special_requirements: Optional[str] = Field(None, max_length=2000)
    transaction_no: str

    @field_validator('zip_code')
    @classmethod
    def validate_zip_code(cls, v):
        if not re.match(r'^\d{5}(-\d{4})?$', v):
            raise ValueError('ZIP code must be 5-digit or ZIP+4 format')
        return v

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

    @field_validator('contact_phone', mode='before')
    @classmethod
    def validate_contact_phone(cls, v):
        if v:
            v = clean_phone(v)
            digits = re.sub(r'\D', '', v)
            if len(digits) < 10 or len(digits) > 15:
                raise ValueError('Phone number must be 10-15 digits')
        return v

    @field_validator('state', mode='before')
    @classmethod
    def validate_state(cls, v):
        if v:
            v = clean_state(v)
            if len(v) != 2 or not v.isupper():
                raise ValueError('State must be 2-character uppercase code')
        return v

class GroupHealthCreate(GroupHealthBase):
    pass

class GroupHealthUpdate(BaseModel):
    company_name: Optional[str] = Field(None, min_length=2, max_length=100)
    industry_sic_code: Optional[str] = Field(None, max_length=10)
    company_address: Optional[str] = Field(None, max_length=500)
    city: Optional[str] = Field(None, max_length=100)
    state: Optional[str] = Field(None, max_length=2)
    zip_code: Optional[str] = Field(None, max_length=10)
    federal_tax_id: Optional[str] = Field(None, max_length=9)
    
    number_of_employees: Optional[int] = Field(None, ge=1)
    number_of_employees_to_be_covered: Optional[int] = Field(None, ge=1)
    average_age_of_employees: Optional[float] = Field(None, ge=18, le=100)
    employee_census_file_path: Optional[str] = Field(None, max_length=500)
    
    type_of_coverage_requested: Optional[str] = Field(None, max_length=500)
    desired_coverage_start_date: Optional[date] = None
    
    current_insurance_carrier: Optional[str] = Field(None, max_length=255)
    current_plan_type: Optional[str] = Field(None, max_length=50)
    monthly_premium_current_plan: Optional[Decimal] = Field(None, decimal_places=2)
    
    contribution_strategy: Optional[str] = Field(None, max_length=50)
    waiting_period_new_employees: Optional[str] = Field(None, max_length=20)
    
    broker_agent_involved: Optional[bool] = None
    broker_agent_name: Optional[str] = Field(None, max_length=255)
    
    contact_person_name: Optional[str] = Field(None, max_length=255)
    contact_email: Optional[EmailStr] = None
    contact_phone: Optional[str] = Field(None, max_length=15)
    preferred_contact_method: Optional[str] = Field(None, max_length=20)
    notes_special_requirements: Optional[str] = Field(None, max_length=2000)
    
    quote_status: Optional[str] = Field(None, max_length=50)
    premium_amount: Optional[Decimal] = Field(None, decimal_places=2)

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