from __future__ import annotations

from typing import Optional, Any, Dict

from analogai.foundation.common.enums.criterion import Criterion
from analogai.foundation.common.enums.certainty import Certainty, certainty_from_value
from analogai.foundation.common.utils.statement_serializers.helpers import modifier_from_criteria, normalize_timezone
from analogai.foundation.common.utils.statement_serializers.helpers.relation_verbalization_map import (
    RELATION_TO_VERBALIZATION,
)
from analogai.foundation.common.utils.statement_serializers.statement_serializer import serialize_statement


def serialize_condition(criteria: Dict[Criterion, Any], timezone: Optional[str] = None) -> str:
    subject = criteria.get(Criterion.SubjectCaption)
    obj = criteria.get(Criterion.ObjectCaption)
    relation = criteria.get(Criterion.Relation)
    if not subject or not obj or not relation:
        return ""

    timezone = normalize_timezone(timezone)
    certainty = criteria.get(Criterion.Certainty)
    modifier = modifier_from_criteria(criteria)
    relation_value = relation.value if hasattr(relation, "value") else str(relation)

    probability = criteria.get(Criterion.RelationProbability)
    certainty_enum = certainty_from_value(certainty)
    if certainty is not None:
        probability = certainty_enum.to_probability()
    elif probability is None:
        probability = 1.0

    if certainty_enum == Certainty.NEGATED and relation_value not in RELATION_TO_VERBALIZATION:
        if relation_value in ("is", "be"):
            relation_value = "is not"
        else:
            relation_value = f"does not {relation_value}"
        probability = 1.0

    return serialize_statement(
        subject_notion_caption=str(subject),
        complement_notion_caption=str(obj),
        relation=relation_value,
        probability=probability,
        modifier=modifier,
        timezone=timezone,
    )
