import logging

from odoo import api, models, fields

_logger = logging.getLogger(__name__)


class EncoachStudentAttempt(models.Model):
    _name = 'encoach.student.attempt'
    _description = 'Student Exam Attempt'

    student_id = fields.Many2one('res.users', required=True, ondelete='cascade', index=True)
    exam_id = fields.Many2one('encoach.exam.custom', ondelete='set null')
    started_at = fields.Datetime(default=fields.Datetime.now)
    completed_at = fields.Datetime()
    status = fields.Selection([
        ('in_progress', 'In Progress'),
        ('completed', 'Completed'),
        ('scoring', 'Scoring'),
        ('scored', 'Scored'),
        ('released', 'Released'),
        ('pending_approval', 'Pending Approval'),
    ], default='in_progress', required=True)
    listening_band = fields.Float()
    reading_band = fields.Float()
    writing_band = fields.Float()
    speaking_band = fields.Float()
    overall_band = fields.Float()
    cefr_level = fields.Selection([
        ('pre_a1', 'Pre-A1'),
        ('a1', 'A1'),
        ('a2', 'A2'),
        ('b1', 'B1'),
        ('b2', 'B2'),
        ('c1', 'C1'),
        ('c2', 'C2'),
    ])
    is_placement = fields.Boolean(default=False)
    entity_id = fields.Many2one('encoach.entity', ondelete='set null')
    released_at = fields.Datetime()
    released_by = fields.Many2one('res.users', ondelete='set null')
    answer_ids = fields.One2many('encoach.student.answer', 'attempt_id')
    score_ids = fields.One2many('encoach.score', 'attempt_id')
    autosave_data = fields.Text()
    feedback_ids = fields.One2many('encoach.feedback', 'attempt_id')

    @api.model
    def _auto_init(self):
        res = super()._auto_init()
        cr = self.env.cr
        for name, ddl in (
            (
                'encoach_student_attempt_student_status_idx',
                "CREATE INDEX IF NOT EXISTS encoach_student_attempt_student_status_idx "
                "ON encoach_student_attempt (student_id, status)",
            ),
            (
                'encoach_student_attempt_exam_status_idx',
                "CREATE INDEX IF NOT EXISTS encoach_student_attempt_exam_status_idx "
                "ON encoach_student_attempt (exam_id, status) WHERE exam_id IS NOT NULL",
            ),
            (
                'encoach_student_attempt_entity_released_idx',
                "CREATE INDEX IF NOT EXISTS encoach_student_attempt_entity_released_idx "
                "ON encoach_student_attempt (entity_id, released_at) "
                "WHERE entity_id IS NOT NULL AND released_at IS NOT NULL",
            ),
        ):
            try:
                cr.execute(ddl)
            except Exception:
                _logger.warning("could not create index %s", name, exc_info=True)
        return res
