from odoo import models, fields, api
from datetime import datetime


class EncoachExamSchedule(models.Model):
    _name = 'encoach.exam.schedule'
    _description = 'Exam Schedule / Assignment Group'
    _order = 'create_date desc'

    name = fields.Char(required=True, size=200)
    exam_id = fields.Many2one('encoach.exam.custom', required=True, ondelete='cascade')
    entity_id = fields.Many2one('encoach.entity', ondelete='set null')

    start_date = fields.Datetime(required=True)
    end_date = fields.Datetime(required=True)

    full_length = fields.Boolean(default=True)
    generate_different = fields.Boolean(default=False)
    auto_release_results = fields.Boolean(default=False)
    auto_start = fields.Boolean(default=False)
    official_exam = fields.Boolean(default=False)
    hide_assignee_details = fields.Boolean(default=False)

    assign_mode = fields.Selection([
        ('entity', 'Entire Entity'),
        ('batch', 'Class / Batch'),
        ('individual', 'Individual Students'),
    ], default='batch', required=True)

    batch_ids = fields.Many2many('op.batch', string='Classes')
    student_ids = fields.Many2many('res.users', 'exam_schedule_student_rel',
                                   'schedule_id', 'user_id', string='Students')

    state = fields.Selection([
        ('planned', 'Planned'),
        ('active', 'Active'),
        ('past', 'Past'),
        ('start_expired', 'Start Expired'),
        ('archived', 'Archived'),
    ], default='planned', required=True, index=True)

    assignment_ids = fields.One2many('encoach.exam.assignment', 'schedule_id')
    assignee_count = fields.Integer(compute='_compute_counts', store=True)
    completed_count = fields.Integer(compute='_compute_counts', store=True)

    @api.depends('assignment_ids', 'assignment_ids.status')
    def _compute_counts(self):
        for rec in self:
            assignments = rec.assignment_ids
            rec.assignee_count = len(assignments)
            rec.completed_count = len(assignments.filtered(lambda a: a.status == 'completed'))

    def update_lifecycle_states(self):
        """Cron job: transition schedules based on current time."""
        now = datetime.now()

        planned = self.search([('state', '=', 'planned'), ('start_date', '<=', now), ('end_date', '>', now)])
        planned.write({'state': 'active'})

        expired_planned = self.search([('state', '=', 'planned'), ('start_date', '<=', now), ('end_date', '<=', now)])
        expired_planned.write({'state': 'start_expired'})

        active_ended = self.search([('state', '=', 'active'), ('end_date', '<=', now)])
        active_ended.write({'state': 'past'})
        for rec in active_ended:
            rec.assignment_ids.filtered(
                lambda a: a.status in ('assigned', 'started')
            ).write({'status': 'expired'})
