import logging

from odoo import api, fields, models

_logger = logging.getLogger(__name__)


class EncoachQuestion(models.Model):
    _name = 'encoach.question'
    _description = 'Question Item'

    skill = fields.Selection([
        ('listening', 'Listening'),
        ('reading', 'Reading'),
        ('writing', 'Writing'),
        ('speaking', 'Speaking'),
        ('grammar', 'Grammar'),
        ('vocabulary', 'Vocabulary'),
        ('math', 'Mathematics'),
        ('it', 'Information Technology'),
    ], required=True)
    source_type = fields.Selection([
        ('passage', 'Passage'),
        ('audio', 'Audio'),
        ('writing_prompt', 'Writing Prompt'),
        ('speaking_card', 'Speaking Card'),
    ])
    source_id = fields.Integer()
    question_type = fields.Selection([
        ('mcq', 'MCQ'),
        ('mcq_multi', 'MCQ Multiple'),
        ('tfng', 'True/False/Not Given'),
        ('ynng', 'Yes/No/Not Given'),
        ('gap_fill', 'Gap Fill'),
        ('short_answer', 'Short Answer'),
        ('form_completion', 'Form Completion'),
        ('note_completion', 'Note Completion'),
        ('map_labelling', 'Map Labelling'),
        ('matching', 'Matching'),
        ('summary_completion', 'Summary Completion'),
        ('heading_matching', 'Heading Matching'),
        ('matching_features', 'Matching Features'),
        ('numerical', 'Numerical'),
        ('expression', 'Expression'),
        ('code_completion', 'Code Completion'),
        ('code_output', 'Code Output'),
        ('sql_query', 'SQL Query'),
        ('matrix', 'Matrix'),
        ('graph', 'Graph'),
    ], required=True)
    stem = fields.Text(required=True)
    options = fields.Text()
    correct_answer = fields.Text()
    marks = fields.Float(default=1.0)
    difficulty = fields.Selection([
        ('easy', 'Easy'),
        ('medium', 'Medium'),
        ('hard', 'Hard'),
    ], required=True)
    status = fields.Selection([
        ('draft', 'Draft'),
        ('active', 'Active'),
        ('retired', 'Retired'),
        ('flagged', 'Flagged'),
    ], default='draft')
    irt_a = fields.Float(default=1.0)
    irt_b = fields.Float(default=0.0)
    irt_c = fields.Float(default=0.25)
    ai_generated = fields.Boolean(default=False)
    ielts_certified = fields.Boolean(default=False)
    format_validated = fields.Boolean(default=False)
    subject_id = fields.Many2one('encoach.subject', ondelete='set null')
    topic_id = fields.Many2one('encoach.topic', ondelete='set null')

    ai_model_used = fields.Char(
        string='AI Model',
        help='LLM model that produced this question (e.g. gpt-4o-mini).',
        index=True,
    )
    ai_prompt_hash = fields.Char(
        string='Prompt Hash',
        help='SHA-256 hex digest of the rendered prompt used to generate this question.',
        index=True,
    )
    ai_log_id = fields.Integer(
        string='AI Generation Log ID',
        help='Row id in encoach.ai.generation.log (soft ref — no FK to avoid cross-module coupling).',
        index=True,
    )
    ai_generated_at = fields.Datetime(string='AI Generated At')
    quality_score = fields.Float(
        string='Quality Score',
        help='Aggregate quality score from automated checkers (0-1).',
    )
    quality_report = fields.Text(
        string='Quality Report (JSON)',
        help='JSON dump of the last QualityChecker + IeltsValidator run.',
    )

    @api.model
    def _auto_init(self):
        res = super()._auto_init()
        cr = self.env.cr
        for name, ddl in (
            (
                'encoach_question_skill_status_idx',
                "CREATE INDEX IF NOT EXISTS encoach_question_skill_status_idx "
                "ON encoach_question (skill, status)",
            ),
            (
                'encoach_question_subject_difficulty_idx',
                "CREATE INDEX IF NOT EXISTS encoach_question_subject_difficulty_idx "
                "ON encoach_question (subject_id, difficulty) WHERE subject_id IS NOT NULL",
            ),
            (
                'encoach_question_ai_prompt_hash_idx',
                "CREATE INDEX IF NOT EXISTS encoach_question_ai_prompt_hash_idx "
                "ON encoach_question (ai_prompt_hash) WHERE ai_prompt_hash IS NOT NULL",
            ),
        ):
            try:
                cr.execute(ddl)
            except Exception:
                _logger.warning("could not create index %s", name, exc_info=True)
        return res
