"""
Entity Tool Class - Handle entity-related operations
"""

import re
import difflib
from typing import Tuple


class EntityUtils:
    """Entity Tool Class"""
    
    @staticmethod
    def entity_link_dict(keyword: str, poi_dict: dict) -> Tuple[str, str]:
        """
        Find matching entities in the POI dictionary based on keywords
        
        Args:
            keyword: Keyword
            poi_dict: POI Dictionary
            
        Returns:
            Tuple[str, str]: (Entity ID, Entity Name)
        """
        import copy
        
        if isinstance(poi_dict, str):
            import json
            try:
                poi_dict = json.loads(poi_dict)
            except json.JSONDecodeError as e:
                print(f"The input poi_dict is not a valid JSON format: {e}")
                return "", ""
                
        cur_poi_dict = copy.deepcopy(poi_dict)
        cur_poi_dict.pop('rule_set_1', None)
        
        if keyword in cur_poi_dict:
            return cur_poi_dict[keyword]["poiid"], keyword
            
        # If there is no direct match, try to find the closest key
        close_matches = difflib.get_close_matches(keyword, cur_poi_dict.keys(), n=1, cutoff=0.15)
        
        if close_matches:
            closest_key = close_matches[0]
            return cur_poi_dict[closest_key]["poiid"], closest_key
        else:
            for k in cur_poi_dict.keys():
                if keyword in k or k in keyword:
                    return cur_poi_dict[k]["poiid"], k
                    
        print(f"No similar keyword found: {keyword}")
        return "", "" 
