from loguru import logger

class MatchResult:
    def __init__(self, top_k_results: list):
        self.results = top_k_results
        self.confidence_level = "low"
        self.message = ""

    def analyze_confidence(self, score_threshold=0.5, margin_threshold=0.1):
        """
        Logic 'Chốt hạ' dựa trên Score và Margin.
        Note: results contain 'distance' (Euclidean), smaller is better.
        But for UI we often use 'similarity' (1 - distance normalized).
        Let's assume input results are sorted by best match.
        """
        if not self.results:
            self.confidence_level = "none"
            self.message = "No matches found."
            return

        # Simple conversion from Euclidean distance to a 'similarity' score for logic
        # This is high-level, actual metric depends on the embedding space.
        def dist_to_sim(d):
            return max(0, 1 - d)

        s1 = dist_to_sim(self.results[0]['distance'])
        
        if len(self.results) > 1:
            s2 = dist_to_sim(self.results[1]['distance'])
            margin = s1 - s2
        else:
            margin = 1.0 # Only one result, high margin

        logger.info(f"Analysis: Top1 Similarity: {s1:.3f}, Margin: {margin:.3f}")

        if s1 > score_threshold and margin > margin_threshold:
            self.confidence_level = "high"
            self.message = "Exact product identified."
            # Only keep the best one for high confidence
            self.results = [self.results[0]]
        elif s1 > (score_threshold - 0.1) and margin < margin_threshold:
            self.confidence_level = "medium"
            self.message = "Multiple similar products found, clarification needed."
            # Keep top 2-3
            self.results = self.results[:3]
        else:
            self.confidence_level = "low"
            self.message = "No exact match found. Showing similar items."

    def to_dict(self):
        return {
            "confidence": self.confidence_level,
            "message": self.message,
            "items": self.results
        }
