# person_step12.py
#
# ICS 33 Spring 2026
# Code Example
#
# This version adds validation to our Person class, by checking in its
# __post_init__ method that its fields have values that meet their
# requirements.

from dataclasses import dataclass
from datetime import date


@dataclass(frozen = True, kw_only = True)
class Person:
    name: str
    birthdate: date


    # Whenever a __post_init__(self) method is present in a dataclass, it's
    # called as the last step of initialization.  We'll use it to make sure
    # that name is a non-empty string and that birthdate is a date.
    def __post_init__(self):
        if type(self.name) is not str:
            raise ValueError(f'name must be a string, but was {type(self.name).__name__}')
        elif len(self.name) == 0:
            raise ValueError(f'name cannot be an empty string')
        elif type(self.birthdate) is not date:
            raise ValueError(f'birthdate must be a date, but was {type(self.birthdate).__name__}')


    def age(self, as_of_date: date) -> int:
        if self.birthdate > as_of_date:
            raise ValueError(f'Person was not born yet on {as_of_date}')

        years_old = as_of_date.year - self.birthdate.year

        if (self.birthdate.month, self.birthdate.day) >= (as_of_date.month, as_of_date.day):
            years_old -= 1

        return years_old
