from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import pandas as pd
import numpy as np
import json


class TagMatcher:
    def __init__(self, tag_data_path):
        # Load and process JSON data
        with open(tag_data_path, 'r') as f:
            data = json.load(f)
        
        # Convert to DataFrame and flatten structure
        self.data = pd.json_normalize(data['tag_guides'])
        
        # Prepare text data for matching
        self.text_data = self.data['name'].tolist()
        self.vectorizer = TfidfVectorizer()
        self._fit_vectorizer()
        
    def _fit_vectorizer(self):
        self.vectorizer.fit(self.text_data)
    
    def find_matches(self, query_text, top_n=5):
        query_vec = self.vectorizer.transform([query_text])
        tag_vecs = self.vectorizer.transform(self.text_data)
        
        similarities = cosine_similarity(query_vec, tag_vecs)
        top_indices = np.argsort(similarities[0])[-top_n:][::-1]
        
        # Return matches with relevant fields
        results = []
        for idx in top_indices:
            match = self.data.iloc[idx]
            results.append({
                'name': match['name'],
                'year_start': match['year_start'],
                'year_end': match['year_end'],
                'images': match['images']
            })
        
        return results
