from typing import Iterator, Optional, Tuple

from analogai.foundation.common.enums import RelationshipType


def _normalize_tag_key(tag_text: str) -> str:
    return tag_text.strip().lower().replace(" ", "_")


def tag_key_to_relationship_type(tag_key: str) -> Optional[RelationshipType]:
    normalized_key = _normalize_tag_key(tag_key)
    if normalized_key.startswith("is_") and normalized_key not in ("is", "is_a", "isa"):
        normalized_key = normalized_key[3:]
    for relationship_type in RelationshipType:
        if relationship_type.name.lower() == normalized_key:
            return relationship_type
        if _normalize_tag_key(relationship_type.value) == normalized_key:
            return relationship_type
    return None


def relationship_type_tag_keys() -> Iterator[Tuple[str, RelationshipType]]:
    for relationship_type in RelationshipType:
        yield relationship_type.value, relationship_type
        key_from_name = relationship_type.name.lower()
        if key_from_name != relationship_type.value:
            yield key_from_name, relationship_type
