# #region FuzzyMatching [TYPE Module] [SEMANTICS fuzzy, matching, rapidfuzz, database, mapping]
#
# @BRIEF Provides utility functions for fuzzy matching database names.
# @LAYER     Core
# @RELATION DEPENDS_ON -> [EXT:Library:rapidfuzz]
#
# @INVARIANT  Confidence scores are returned as floats between 0.0 and 1.0.


from rapidfuzz import fuzz, process


# #region suggest_mappings [TYPE Function]
# @BRIEF Suggests mappings between source and target databases using fuzzy matching.
# @PRE      source_databases and target_databases are lists of dictionaries with 'uuid' and 'database_name'.
# @POST     Returns a list of suggested mappings with confidence scores.
def suggest_mappings(source_databases: list[dict], target_databases: list[dict], threshold: int = 60) -> list[dict]:
    """
    Suggest mappings between source and target databases using fuzzy matching.
    """
    suggestions = []
    if not target_databases:
        return suggestions

    target_names = [db['database_name'] for db in target_databases]

    for s_db in source_databases:
        # Use token_sort_ratio as decided in research.md
        match = process.extractOne(
            s_db['database_name'],
            target_names,
            scorer=fuzz.token_sort_ratio
        )

        if match:
            name, score, index = match
            if score >= threshold:
                suggestions.append({
                    "source_db": s_db['database_name'],
                    "target_db": target_databases[index]['database_name'],
                    "source_db_uuid": s_db['uuid'],
                    "target_db_uuid": target_databases[index]['uuid'],
                    "confidence": score / 100.0
                })

    return suggestions
# #endregion suggest_mappings

# #endregion FuzzyMatching
