import json
import logging

try:
    from odoo.addons.encoach_ai.services.openai_service import OpenAIService
except ImportError:
    OpenAIService = None

try:
    from odoo.addons.encoach_quality_gate.services.content_gate import ContentSourceGate
except ImportError:
    ContentSourceGate = None

_logger = logging.getLogger(__name__)


class EnglishPipeline:
    """AI content generation pipeline for General English courses."""

    def __init__(self, env):
        self.env = env
        self.ai = OpenAIService(env)

    def generate_content(self, env, gap_profile, cefr_level):
        """Generate General English content based on gap analysis.

        Args:
            env: Odoo environment.
            gap_profile: dict with 'skill_gaps' list describing weak areas.
            cefr_level: target CEFR level string (e.g. 'B1').

        Returns:
            dict with generated content.
        """
        skill_gaps = gap_profile.get('skill_gaps', [])
        gaps_description = ', '.join(skill_gaps) if skill_gaps else 'general skills'

        messages = [
            {'role': 'system', 'content': (
                'You are an expert English language curriculum designer. '
                'Return JSON with keys: "title", "objectives", "units" '
                '(each unit has "topic", "grammar_focus", "vocabulary", '
                '"reading_text", "exercises").'
            )},
            {'role': 'user', 'content': (
                f'Generate a General English course at CEFR {cefr_level} level. '
                f'Focus on these gap areas: {gaps_description}. '
                f'Include practical, real-world content appropriate for the level.'
            )},
        ]

        try:
            content = self.ai.chat_json(messages, temperature=0.8)
        except Exception as e:
            _logger.error("English content generation failed: %s", e)
            env['encoach.ai.generation.log'].create({
                'course_type': 'general_english',
                'brief': json.dumps(gap_profile),
                'status': 'rejected',
                'error_log': str(e),
            })
            return {'error': str(e)}

        resource = env['encoach.ai.generation.log'].create({
            'course_type': 'general_english',
            'brief': json.dumps(gap_profile),
            'status': 'quality_check',
            'attempts': 1,
        })

        # Apply content source gate logic
        if ContentSourceGate is not None:
            try:
                ContentSourceGate.apply_gate(resource)
            except Exception as e:
                _logger.warning("ContentSourceGate.apply_gate failed: %s", e)

        return content

    def quality_check(self, env, content, cefr_level):
        """Run quality gate checks on generated content.

        Args:
            env: Odoo environment.
            content: dict of generated content to validate.
            cefr_level: target CEFR level for alignment check.

        Returns:
            dict with 'passed' bool and 'issues' list.
        """
        issues = []

        if not content.get('units'):
            issues.append('No units generated')
        else:
            for i, unit in enumerate(content['units'], 1):
                if not unit.get('exercises'):
                    issues.append(f'Unit {i} has no exercises')
                if not unit.get('reading_text'):
                    issues.append(f'Unit {i} has no reading text')

        if not content.get('objectives'):
            issues.append('No learning objectives defined')

        messages = [
            {'role': 'system', 'content': (
                'You are a CEFR alignment expert. Return JSON with keys: '
                '"aligned" (bool) and "issues" (list of strings).'
            )},
            {'role': 'user', 'content': (
                f'Check if this content is aligned with CEFR {cefr_level}: '
                f'{json.dumps(content)}'
            )},
        ]

        try:
            alignment = self.ai.chat_json(messages, temperature=0.3)
            if not alignment.get('aligned'):
                issues.extend(alignment.get('issues', ['CEFR misalignment detected']))
        except Exception as e:
            _logger.warning("CEFR alignment check failed: %s", e)
            issues.append(f'CEFR alignment check error: {e}')

        return {'passed': len(issues) == 0, 'issues': issues}
