"""Service module for handling exam data operations."""

import json
import os
from typing import Dict, Any, Optional


class ExamService:
    """Service class for managing exam data."""
    
    def __init__(self, asset_path: str):
        """
        Initialize ExamService with asset path.
        
        Args:
            asset_path: Path to the directory containing exam assets
        """
        self.asset_path = asset_path
    
    def load_exam_data(self) -> Optional[Dict[str, Any]]:
        """
        Load exam data from exam.json file.
        
        Returns:
            Dictionary containing exam data or None if file not found
        """
        exam_file_path = os.path.join(self.asset_path, "exam.json")
        print(f"exam_file_path is: {exam_file_path}")
        print(f"asset path is: {self.asset_path}")
        try:
            with open(exam_file_path, 'r', encoding='utf-8') as file:
                data = json.load(file)
                return data
        except FileNotFoundError:
            print(f"File not found: {exam_file_path}")
            return None
        except json.JSONDecodeError:
            print(f"JSON decode error: {exam_file_path}")
            return None
        except Exception as e:
            print(f"Error: {e}")
            return None
    
    def get_exam_summary(self, exam_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        Extract exam summary information.
        
        Args:
            exam_data: Full exam data dictionary
            
        Returns:
            Dictionary containing exam summary
        """
        if not exam_data or not exam_data.get('success'):
            return {}
        
        lab = exam_data.get('data', {}).get('lab', {})
        
        return {
            'name': lab.get('name', 'N/A'),
            'duration': lab.get('examDurationInMinutes', 0),
            'difficulty': lab.get('difficulty', 'N/A').capitalize(),
            'number_of_questions': lab.get('number_of_questions', 0),
            'total_marks': lab.get('total_marks', 0),
            'passing_score': lab.get('passing_score', 0)
        }
    
    def get_questions_with_answers(self, exam_data: Dict[str, Any]) -> list:
        """
        Extract questions with their answers and performance data.
        
        Args:
            exam_data: Full exam data dictionary
            
        Returns:
            List of dictionaries containing question details
        """
        if not exam_data or not exam_data.get('success'):
            return []
        
        lab = exam_data.get('data', {}).get('lab', {})
        questions = lab.get('questions', [])
        
        result = []
        for question in questions:
            question_data = {
                'order': question.get('question_order', 0),
                'title': question.get('question_title', 'N/A'),
                'question': question.get('question', ''),
                'answer_explanation': question.get('answer_explanation', ''),
                'performance_data': {}
            }
            
            # Extract performance data
            if question.get('question_type') == 'performance':
                perf_data = question.get('performance_data', {})
                question_data['performance_data'] = {
                    'namespace': perf_data.get('namespace', 'N/A'),
                    'machine_hostname': perf_data.get('machine_hostname', 'N/A')
                }
            
            result.append(question_data)
        
        # Sort by question order
        result.sort(key=lambda x: x['order'])
        
        return result
