from typing import Optional

from analogai.foundation.core.value_objects.modifier import Modifier
from analogai.foundation.common.enums.deontic_modality import DeonticModality
from analogai.deepthink.presentation.utils.time_parser import TimeParser

from analogai.deepthink.application.value_objects.user_agent import UserAgent
from analogai.deepthink.presentation.parsers.propagated_sentence import PropagatedData


def build_modifier_from_parsed(parsed_data: PropagatedData, user_agent: UserAgent) -> Optional[Modifier]:
    location = parsed_data.location or None
    deontic_str = parsed_data.deontic_modality or None
    from_time_str = parsed_data.from_time or None
    to_time_str = parsed_data.to_time or None
    time_str = parsed_data.time or None

    if not (location or deontic_str or from_time_str or to_time_str or time_str):
        return None

    if not from_time_str and not to_time_str and time_str:
        from_time_str = time_str
        to_time_str = time_str
    elif from_time_str and not to_time_str:
        to_time_str = from_time_str
    elif to_time_str and not from_time_str:
        from_time_str = to_time_str

    timezone = user_agent.timezone
    from_time = TimeParser.parse(from_time_str, timezone=timezone) if from_time_str else None
    to_time = TimeParser.parse(to_time_str, timezone=timezone) if to_time_str else None
    deontic = None
    if deontic_str:
        try:
            deontic = DeonticModality(deontic_str.lower())
        except (ValueError, AttributeError):
            pass
    return Modifier(
        location=location,
        deontic_modality=deontic,
        from_time=from_time,
        to_time=to_time,
    )
