import sounddevice as sd
from pocketsphinx import AudioFile, SpeakerRecognizer
from nlp import analyze_text

class AuditoryProcessor:
    def __init__(self):
        self.recognizer = SpeakerRecognizer()
        self.audio_path = "audio_recording.wav"
        self.recognized_text = ""
        self.current_speaker = None
        self.commands = {
            "hello": self.handle_greeting,
            "help": self.handle_help,
            "exit": self.handle_exit
        }

    def capture_audio(self):
        """Captures audio input from microphone and saves it to a file."""
        print("Recording audio...")
        sd.play(0.5, 44100)  # Play beep sound to indicate recording
        sd.wait()  # Wait for recording to complete
        recording = sd.rec(
            int=2,
            fs=44100,
            channels=2,
            blocking=True
        )
        print("Audio captured successfully")
        return recording

    def recognize_speech(self, audio_data):
        """Converts audio data into text using speech recognition."""
        with AudioFile(audio_path) as source:
            audio = source.read()
            result = self.recognizer.recognize(audio)
            if result:
                self.recognized_text = result
            else:
                raise ValueError("Speech could not be recognized")

    def add_reference_audio(self, speaker_id, audio_path):
        """Adds reference audio for speaker identification."""
        SpeakerRecognizer.addAudio(
            speaker_id,
            audio_path,
            self.recognizer
        )

    def enroll_speaker(self, speaker_id):
        """Enrolls a speaker into the recognition system."""
        SpeakerRecognizer.enroll(speaker_id, self.recognizer)

    def identify_speaker(self, audio_path):
        """Identifies the current speaker based on audio input."""
        return SpeakerRecognizer.identify(
            audio_path,
            self.recognizer
        )

    def analyze_speech(self):
        """Analyzes the content of recognized speech and extracts insights."""
        analysis = analyze_text(self.recognized_text)
        self.current_sentiment = analysis["sentiment"]
        self.key_topics = analysis["key_topics"]
        self.intent = analysis["intent"]

    def handle_command(self, command):
        """Processes and executes commands based on recognized speech."""
        if command in self.commands:
            return self.commands[command]()
        else:
            raise ValueError(f"Command not recognized: {command}")

    def play_beep(self):
        """Plays a beep sound to indicate system responses."""
        sd.play(0.5, 44100)
        sd.wait()

    def handle_greeting(self):
        """Handles the 'hello' command."""
        self.play_beep()
        return "Hello! How can I assist you today?"

    def handle_help(self):
        """Handles the 'help' command."""
        self.play_beep()
        return "I'm here to help. What would you like me to do?"

    def handle_exit(self):
        """Handles the 'exit' command."""
        self.play_beep()
        return "Goodbye! Have a great day!"