from typing import Optional
from datetime import datetime
from analogai.foundation.core.value_objects.time import Time


class TimeConverter:
    
    @staticmethod
    def to_datetime(time_obj: Time, reference: datetime) -> Optional[datetime]:
        year = time_obj.year if time_obj.year is not None else reference.year
        month = time_obj.month if time_obj.month is not None else reference.month
        day = time_obj.day if time_obj.day is not None else 1
        hour = time_obj.hour if time_obj.hour is not None else 0
        minute = time_obj.minute if time_obj.minute is not None else 0

        try:
            dt = datetime(year, month, day, hour, minute)
            if reference.tzinfo is not None:
                dt = dt.replace(tzinfo=reference.tzinfo)
            return dt
        except ValueError:
            return None
    
    @staticmethod
    def has_time_data(time_obj: Optional[Time]) -> bool:
        if time_obj is None:
            return False
        return any([
            time_obj.year is not None,
            time_obj.month is not None,
            time_obj.day is not None,
            time_obj.hour is not None,
            time_obj.minute is not None
        ])
