import logging

_logger = logging.getLogger(__name__)


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

    @staticmethod
    def transcribe_audio(audio_path):
        """Transcribe audio using Whisper."""
        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:
            _logger.warning("whisper not installed")
            return {'text': '', 'language': 'en', 'segments': [], 'error': 'Whisper not available'}

    @staticmethod
    def evaluate_speaking(transcription, rubric_criteria, target_band=6.0):
        """Evaluate speaking using OpenAI GPT."""
        try:
            import openai

            prompt = (
                "You are an IELTS speaking examiner. Evaluate the following speaking response.\n\n"
                f"Target Band: {target_band}\n\n"
                f"Rubric Criteria:\n{rubric_criteria}\n\n"
                f"Transcription:\n{transcription}\n\n"
                "Provide scores for each criterion (0-9 scale) and detailed feedback.\n"
                "Return JSON format:\n"
                "{\n"
                '    "fluency_coherence": {"score": X, "feedback": "..."},\n'
                '    "lexical_resource": {"score": X, "feedback": "..."},\n'
                '    "grammatical_range": {"score": X, "feedback": "..."},\n'
                '    "pronunciation": {"score": X, "feedback": "..."},\n'
                '    "overall_band": X,\n'
                '    "general_feedback": "..."\n'
                "}"
            )

            client = openai.OpenAI()
            response = client.chat.completions.create(
                model="gpt-4",
                messages=[
                    {"role": "system", "content": "You are an expert IELTS speaking examiner."},
                    {"role": "user", "content": prompt},
                ],
                temperature=0.3,
            )

            import json
            result = json.loads(response.choices[0].message.content)
            return result

        except ImportError:
            _logger.warning("openai not installed")
            return {'overall_band': 0, 'general_feedback': 'AI evaluation not available', 'error': 'OpenAI not available'}
        except Exception as e:
            _logger.error("Speaking evaluation error: %s", e)
            return {'overall_band': 0, 'general_feedback': f'Evaluation error: {e}'}
