import json
import os


class AnswerDatabase:
    """
    Simple local database for storing and retrieving answers
    """

    def __init__(self, db_file="answers_db.json"):
        self.db_file = db_file
        self.data = self._load_database()

    def _load_database(self):
        """Load database from file"""
        if os.path.exists(self.db_file):
            try:
                with open(self.db_file, 'r') as f:
                    return json.load(f)
            except:
                return {}
        return {}

    def save_database(self):
        """Save database to file"""
        try:
            with open(self.db_file, 'w') as f:
                json.dump(self.data, f, indent=2)
            return True
        except:
            return False

    def add_answer(self, question, answer):
        """Add answer to database"""
        self.data[question] = answer
        self.save_database()

    def get_answer(self, question):
        """Get answer from database"""
        return self.data.get(question)

    def search_similar(self, question, threshold=0.8):
        """
        Search for similar questions in database
        This is a simple implementation - you might want to use more advanced similarity checking
        """
        # Simple keyword-based similarity (you can improve this)
        question_words = set(question.lower().split())
        best_match = None
        best_score = 0

        for stored_question in self.data.keys():
            stored_words = set(stored_question.lower().split())
            common_words = question_words.intersection(stored_words)
            similarity = len(common_words) / max(len(question_words), len(stored_words))

            if similarity > best_score and similarity >= threshold:
                best_score = similarity
                best_match = stored_question

        if best_match:
            return self.data[best_match]
        return None