import json
import os
from typing import Dict, List, Any, Optional
from pathlib import Path

class JSONHandler:
    def __init__(self, base_path: str = "storage"):
        self.base_path = Path(base_path)

        # Create directories if they don't exist
        self._create_directories()

    def _get_storage_paths(self, is_admin: int):
        """Get storage paths based on user type"""
        user_type = "admin" if is_admin == 1 else "learner"
        user_path = self.base_path / user_type

        return {
            'scenarios': user_path / "scenarios",
            'conversations': user_path / "conversations",
            'assessments': user_path / "assessments"
        }

    def _create_directories(self):
        """Create storage directories for both admin and learner"""
        for is_admin in [0, 1]:
            paths = self._get_storage_paths(is_admin)
            for path in paths.values():
                path.mkdir(parents=True, exist_ok=True)

    def save_scenario(self, scenario_data: Dict[str, Any], is_admin: int, session_id: str) -> bool:
        """Save scenario to JSON file using session_id"""
        try:
            print(f"DEBUG JSONHandler.save_scenario: session_id='{session_id}' (type: {type(session_id)})")
            paths = self._get_storage_paths(is_admin)
            filename = f"scenario_{session_id}.json"
            print(f"DEBUG JSONHandler.save_scenario: filename='{filename}'")
            filepath = paths['scenarios'] / filename

            with open(filepath, 'w', encoding='utf-8') as f:
                json.dump(scenario_data, f, indent=2, ensure_ascii=False)
            return True
        except Exception as e:
            print(f"Error saving scenario: {e}")
            return False

    def load_scenario(self, session_id: str, is_admin: int) -> Optional[Dict[str, Any]]:
        """Load scenario from JSON file using session_id"""
        try:
            paths = self._get_storage_paths(is_admin)
            filename = f"scenario_{session_id}.json"
            filepath = paths['scenarios'] / filename

            if not filepath.exists():
                return None

            with open(filepath, 'r', encoding='utf-8') as f:
                return json.load(f)
        except Exception as e:
            print(f"Error loading scenario: {e}")
            return None

    def list_scenarios(self, is_admin: int) -> List[Dict[str, Any]]:
        """List all available scenarios for user type"""
        scenarios = []
        try:
            paths = self._get_storage_paths(is_admin)
            for filepath in paths['scenarios'].glob("scenario_*.json"):
                with open(filepath, 'r', encoding='utf-8') as f:
                    scenario = json.load(f)
                    scenarios.append({
                        'session_id': scenario.get('session_id', filepath.stem.replace('scenario_', '')),
                        'category': scenario['category'],
                        'objective': scenario['objective'],
                        'created_at': scenario['created_at']
                    })
        except Exception as e:
            print(f"Error listing scenarios: {e}")

        return sorted(scenarios, key=lambda x: x['created_at'], reverse=True)

    def save_conversation(self, session_id: str, conversation_data: Dict[str, Any], is_admin: int) -> bool:
        """Save conversation to JSON file"""
        try:
            print(f"DEBUG JSONHandler.save_conversation: session_id='{session_id}' (type: {type(session_id)})")
            paths = self._get_storage_paths(is_admin)
            filename = f"conversation_{session_id}.json"
            print(f"DEBUG JSONHandler.save_conversation: filename='{filename}'")
            filepath = paths['conversations'] / filename
            print(f"DEBUG JSONHandler.save_conversation: full_filepath='{filepath}'")
            print(f"DEBUG JSONHandler.save_conversation: absolute_path='{filepath.absolute()}'")

            with open(filepath, 'w', encoding='utf-8') as f:
                json.dump(conversation_data, f, indent=2, ensure_ascii=False)
            return True
        except Exception as e:
            print(f"Error saving conversation: {e}")
            return False

    def load_conversation(self, session_id: str, is_admin: int) -> Optional[Dict[str, Any]]:
        """Load conversation from JSON file"""
        try:
            paths = self._get_storage_paths(is_admin)
            filename = f"conversation_{session_id}.json"
            filepath = paths['conversations'] / filename

            if not filepath.exists():
                return None

            with open(filepath, 'r', encoding='utf-8') as f:
                return json.load(f)
        except Exception as e:
            print(f"Error loading conversation: {e}")
            return None

    def delete_conversation(self, session_id: str, is_admin: int) -> bool:
        """Delete conversation file"""
        try:
            paths = self._get_storage_paths(is_admin)
            filename = f"conversation_{session_id}.json"
            filepath = paths['conversations'] / filename

            if filepath.exists():
                filepath.unlink()  # Delete the file
                print(f"DEBUG: Conversation file deleted: {filepath}")
                return True
            else:
                print(f"DEBUG: Conversation file not found: {filepath}")
                return False
        except Exception as e:
            print(f"Error deleting conversation: {e}")
            return False

    def delete_scenario(self, session_id: str, is_admin: int) -> bool:
        """Delete scenario file"""
        try:
            paths = self._get_storage_paths(is_admin)
            filename = f"scenario_{session_id}.json"
            filepath = paths['scenarios'] / filename

            if filepath.exists():
                filepath.unlink()  # Delete the file
                print(f"DEBUG: Scenario file deleted: {filepath}")
                return True
            else:
                print(f"DEBUG: Scenario file not found: {filepath}")
                return False
        except Exception as e:
            print(f"Error deleting scenario: {e}")
            return False

    def delete_assessment(self, session_id: str, is_admin: int) -> bool:
        """Delete assessment file"""
        try:
            paths = self._get_storage_paths(is_admin)
            filename = f"assessment_{session_id}.json"
            filepath = paths['assessments'] / filename

            if filepath.exists():
                filepath.unlink()  # Delete the file
                print(f"DEBUG: Assessment file deleted: {filepath}")
                return True
            else:
                print(f"DEBUG: Assessment file not found: {filepath}")
                return False
        except Exception as e:
            print(f"Error deleting assessment: {e}")
            return False

    def save_assessment(self, assessment_data: Dict[str, Any], is_admin: int) -> bool:
        """Save assessment to JSON file"""
        try:
            print(f"DEBUG JSONHandler.save_assessment: session_id='{assessment_data['session_id']}', is_admin={is_admin}")
            paths = self._get_storage_paths(is_admin)
            filename = f"assessment_{assessment_data['session_id']}.json"
            print(f"DEBUG JSONHandler.save_assessment: filename='{filename}'")
            filepath = paths['assessments'] / filename
            print(f"DEBUG JSONHandler.save_assessment: filepath='{filepath}'")

            with open(filepath, 'w', encoding='utf-8') as f:
                json.dump(assessment_data, f, indent=2, ensure_ascii=False)
            return True
        except Exception as e:
            print(f"Error saving assessment: {e}")
            return False

    def load_assessment(self, session_id: str, is_admin: int) -> Optional[Dict[str, Any]]:
        """Load assessment from JSON file"""
        try:
            paths = self._get_storage_paths(is_admin)
            filename = f"assessment_{session_id}.json"
            filepath = paths['assessments'] / filename

            if not filepath.exists():
                return None

            with open(filepath, 'r', encoding='utf-8') as f:
                return json.load(f)
        except Exception as e:
            print(f"Error loading assessment: {e}")
            return None

    def list_assessments(self, is_admin: int) -> List[Dict[str, Any]]:
        """List all assessments with summary info for user type"""
        assessments = []
        try:
            paths = self._get_storage_paths(is_admin)
            for filepath in paths['assessments'].glob("assessment_*.json"):
                with open(filepath, 'r', encoding='utf-8') as f:
                    assessment = json.load(f)
                    assessments.append({
                        'session_id': assessment['session_id'],
                        'scenario_id': assessment.get('scenario_id', assessment['session_id']),
                        'overall_score': assessment['overall_score'],
                        'performance_level': assessment['performance_level'],
                        'created_at': assessment['created_at']
                    })
        except Exception as e:
            print(f"Error listing assessments: {e}")
        
        return sorted(assessments, key=lambda x: x['created_at'], reverse=True)
