#!/usr/bin/env python3
"""
Fuzzy matching script using fuzzywuzzy library
Called from PHP to calculate similarity scores
"""

import sys
import json
import warnings

# Suppress warnings from fuzzywuzzy
warnings.filterwarnings('ignore')

try:
    from fuzzywuzzy import fuzz
except ImportError:
    print(json.dumps({"error": "fuzzywuzzy library not installed. Install with: pip3 install fuzzywuzzy python-Levenshtein"}))
    sys.exit(1)

def calculate_partial_ratio(text1, text2):
    """
    Calculate partial_ratio using fuzzywuzzy (same as Python search_engines.py)
    Returns score 0-100
    """
    if not text1 or not text2:
        return 0
    
    # Use partial_ratio (same as Python code: fuzz.partial_ratio)
    score = fuzz.partial_ratio(text1, text2)
    return int(score)

def main():
    """
    Main function to handle command line arguments
    Usage: python fuzzy_match.py "text1" "text2" [threshold]
    Returns JSON with match result and score
    """
    if len(sys.argv) < 3:
        result = {
            "error": "Usage: python fuzzy_match.py <text1> <text2> [threshold]",
            "match": False,
            "score": 0
        }
        print(json.dumps(result))
        sys.exit(1)
    
    text1 = sys.argv[1]
    text2 = sys.argv[2]
    threshold = int(sys.argv[3]) if len(sys.argv) > 3 else 80
    
    score = calculate_partial_ratio(text1, text2)
    match = score >= threshold
    
    result = {
        "match": match,
        "score": score,
        "text1": text1,
        "text2": text2,
        "threshold": threshold
    }
    
    print(json.dumps(result))
    sys.exit(0)

if __name__ == "__main__":
    main()

