"""
Format evaluator - evaluate the correctness of the response format
"""

from typing import Dict, Any, Tuple
from .base_evaluator import BaseEvaluator
from utils.itinerary_parser import ItineraryParser
from utils.poi_analyzer import POIAnalyzer


class FormatEvaluator(BaseEvaluator):
    """Format Evaluator Class"""
    
    def __init__(self, format_reward: int = 1, poi_analyzer: POIAnalyzer = None):
        """
        Initialize Format Evaluator
        
        Args:
            format_reward: Format Correctness Reward Score
            poi_analyzer: POI Analyzer Instance, create new instance if None
        """
        super().__init__("FormatEvaluator")
        self.format_reward = format_reward
        self.poi_analyzer = poi_analyzer if poi_analyzer is not None else POIAnalyzer()

    def evaluate(self, data: Dict[str, Any]) -> Tuple[float, Dict[str, Any]]:
        """
        Evaluate Response Format
        
        Args:
            data: Dictionary containing the following keys:
                - solution_str: Original Response String
                - poi_dict: POI Dictionary
                
        Returns:
            Tuple[float, Dict]: (Format Score, Evaluation Details)
        """
        solution_str = data.get("solution_str", "")
        poi_dict = data.get("poi_dict", {})
        # Extract Model Answer
        prompt_str, answer_text, processed_str = ItineraryParser.extract_solution(solution_str)
        
        # Validate Response Structure
        poi_dict_json = poi_dict
        if isinstance(poi_dict_json, str):
            import json
            try:
                poi_dict_json = json.loads(poi_dict_json)
            except Exception as e:
                print(f"Load JSON Error: {e}")
                return -abs(self.format_reward), {"error": "JSON Parsing Failed"}

        format_correct, validation_results, itinerary = ItineraryParser.validate_response_structure(
            answer_text, poi_dict_json, self.poi_analyzer
        )
        
        # Adjust Scoring Standard: Format Correct +1, Format Incorrect -1 (consistent with old version)
        format_score = self.format_reward if format_correct else -abs(self.format_reward)
        
        details = {
            "format_correct": format_correct,
            "validation_results": validation_results,
            "itinerary": itinerary,
            # "prompt_str": prompt_str,
            # "answer_text": answer_text
        }
        
        return format_score, details, prompt_str, answer_text