from pydantic import BaseModel, Field, field_validator, EmailStr, computed_field
from typing import Optional, List, Dict
from datetime import date, datetime
from app.core.base_schema import BaseInsuranceResponse, BaseInsuranceUpdate, MaskedFieldsMixin
from app.core.encryption import mask_email, mask_phone
import re

class DependentInfo(BaseModel):
    name: str = Field(..., min_length=1, max_length=200)
    date_of_birth: date
    gender: str
    relationship: str

class HealthInsuranceCreate(BaseModel):
    # Personal Information
    full_name: str = Field(..., min_length=1, max_length=200)
    date_of_birth: date
    gender: str = Field(..., min_length=1)
    email: EmailStr
    phone_number: str = Field(..., max_length=20)
    
    # Address & Lifestyle
    residential_address: str = Field(..., min_length=1, max_length=500)
    zip_code: str = Field(..., min_length=5, max_length=5)
    tobacco_usage: bool
    current_health_plan: Optional[str] = Field(None, max_length=100)
    takes_prescription_meds: Optional[bool] = None
    
    # Household & Income
    estimated_annual_income: Optional[float] = Field(None, ge=0)
    household_size: int = Field(..., ge=1)
    add_dependents: bool
    dependent_info: Optional[List[DependentInfo]] = None
    
    # Coverage Preferences
    coverage_start_date: date
    preferred_plan_type: Optional[List[str]] = None
    preferred_insurance_carriers: Optional[List[str]] = None
    primary_doctor_name: Optional[str] = Field(None, max_length=200)
    top_health_concerns: Optional[List[str]] = None
    monthly_budget_premium: Optional[float] = Field(None, ge=0)
    
    # Consent
    consent_to_share: bool
    lead_source: Optional[str] = Field(None, description="Where did you hear about us?")

    @field_validator('phone_number')
    @classmethod
    def validate_phone(cls, v):
        # pattern = r'^\+?1?-?\(?\d{3}\)?-?\d{3}-?\d{4}$'
        pattern = r'^\(\d{3}\) \d{3}-\d{4}$'
        if not re.match(pattern, v):
            raise ValueError('Phone number must be valid format')
        return v

    @field_validator('date_of_birth')
    @classmethod
    def validate_age(cls, v):
        today = date.today()
        age = today.year - v.year - ((today.month, today.day) < (v.month, v.day))
        if age < 18:
            raise ValueError('Must be at least 18 years old')
        return v

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

    @field_validator('coverage_start_date')
    @classmethod
    def validate_start_date(cls, v):
        if v < date.today():
            raise ValueError('Coverage start date cannot be in the past')
        return v

    @field_validator('dependent_info')
    @classmethod
    def validate_dependents(cls, v, info):
        if info.data.get('add_dependents') and not v:
            raise ValueError('Dependent information required when adding dependents')
        return v

class HealthInsuranceResponse(BaseInsuranceResponse, MaskedFieldsMixin):
    # Personal Information
    full_name: str
    date_of_birth: date
    gender: str
    email: str
    phone_number: str
    
    # Address & Lifestyle
    residential_address: str
    zip_code: str
    tobacco_usage: bool
    current_health_plan: Optional[str]
    takes_prescription_meds: Optional[bool]
    
    # Household & Income
    estimated_annual_income: Optional[float]
    household_size: int
    add_dependents: bool
    dependent_info: Optional[List[DependentInfo]]
    
    # Coverage Preferences
    coverage_start_date: date
    preferred_plan_type: Optional[List[str]]
    preferred_insurance_carriers: Optional[List[str]]
    primary_doctor_name: Optional[str]
    top_health_concerns: Optional[List[str]]
    monthly_budget_premium: Optional[float]
    
    # Consent
    consent_to_share: bool
    lead_source: Optional[str] = None

class HealthInsuranceUpdate(BaseInsuranceUpdate):
    # Personal Information
    full_name: Optional[str] = Field(None, min_length=1, max_length=200)
    date_of_birth: Optional[date] = None
    gender: Optional[str] = Field(None, min_length=1)
    email: Optional[EmailStr] = None
    phone_number: Optional[str] = Field(None, max_length=20)
    
    # Address & Lifestyle
    residential_address: Optional[str] = Field(None, min_length=1, max_length=500)
    zip_code: Optional[str] = Field(None, min_length=5, max_length=5)
    tobacco_usage: Optional[bool] = None
    current_health_plan: Optional[str] = Field(None, max_length=100)
    takes_prescription_meds: Optional[bool] = None
    
    # Household & Income
    estimated_annual_income: Optional[float] = Field(None, ge=0)
    household_size: Optional[int] = Field(None, ge=1)
    add_dependents: Optional[bool] = None
    dependent_info: Optional[List[DependentInfo]] = None
    
    # Coverage Preferences
    coverage_start_date: Optional[date] = None
    preferred_plan_type: Optional[List[str]] = None
    preferred_insurance_carriers: Optional[List[str]] = None
    primary_doctor_name: Optional[str] = Field(None, max_length=200)
    top_health_concerns: Optional[List[str]] = None
    monthly_budget_premium: Optional[float] = Field(None, ge=0)
    
    # Consent
    consent_to_share: Optional[bool] = None
    lead_source: Optional[str] = None