"""AI-powered speaking assessment using encoach_ai services."""

import logging

_logger = logging.getLogger(__name__)


class SpeakingEvaluator:
    """AI-powered speaking assessment using Whisper + GPT via encoach_ai."""

    def __init__(self, env=None):
        self.env = env

    def transcribe_audio(self, audio_path_or_bytes):
        """Transcribe audio using the encoach_ai WhisperService."""
        try:
            from odoo.addons.encoach_ai.services.whisper_service import WhisperService
            whisper = WhisperService(self.env)
            if isinstance(audio_path_or_bytes, (bytes, bytearray)):
                return whisper.transcribe(audio_path_or_bytes, use_api=True)
            with open(audio_path_or_bytes, "rb") as f:
                return whisper.transcribe(f.read(), use_api=True)
        except ImportError:
            _logger.warning("encoach_ai not installed, falling back to direct whisper")
            return self._fallback_transcribe(audio_path_or_bytes)
        except Exception as e:
            _logger.error("Transcription error: %s", e)
            return {"text": "", "language": "en", "segments": [], "error": str(e)}

    def evaluate_speaking(self, transcription, rubric_criteria, target_band=6.0):
        """Evaluate speaking using encoach_ai OpenAIService."""
        try:
            from odoo.addons.encoach_ai.services.openai_service import OpenAIService
            ai = OpenAIService(self.env)
            result = ai.grade_speaking(
                f"Target Band: {target_band}\n{rubric_criteria}",
                transcription,
            )
            return result
        except ImportError:
            _logger.warning("encoach_ai not installed")
            return {"overall_band": 0, "feedback": "AI evaluation not available"}
        except Exception as e:
            _logger.error("Speaking evaluation error: %s", e)
            return {"overall_band": 0, "feedback": f"Evaluation error: {e}"}

    @staticmethod
    def _fallback_transcribe(audio_path):
        """Direct whisper fallback if encoach_ai is not available."""
        try:
            import whisper
            model = whisper.load_model("base")
            result = model.transcribe(audio_path)
            return {
                "text": result["text"],
                "language": result.get("language", "en"),
                "segments": result.get("segments", []),
            }
        except ImportError:
            return {"text": "", "language": "en", "segments": [], "error": "Whisper not available"}
