from typing import Iterator, Optional, Tuple

from analogai.foundation.common.enums import RelationshipType


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


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


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