from odoo import models, fields, api, _
from odoo.tools import DEFAULT_SERVER_DATE_FORMAT
from dateutil.relativedelta import relativedelta as rd
from datetime import datetime, date


class EducationStatus(models.Model):
    _name = 'education.status'
    _order = 'education_status_type asc, name desc'

    mother_grant_benefit_id = fields.Many2one('grant.benefit', string='Grant Benefit')
    replacement_grant_benefit_id = fields.Many2one('grant.benefit', string='Grant Benefit')
    family_member_id = fields.Many2one('family.member', string='Grant Benefit')

    name = fields.Char(
        string="Sequence",
        default="/",
        readonly=True,
        copy=False,
        index=True
    )

    education_status_type = fields.Selection(
        selection=[
            ('current', 'Current'),
            ('previous', 'Previous')
        ],
        required=False, compute="_compute_education_status_type", store=True
    )
    education_status = fields.Selection(
        string='Education Status',
        selection=[
            ('educated', 'Educated'),
            ('illiterate', 'Illiterate'),
            ('under_study_age', 'Under Study Age')
        ],
        compute="_compute_education_status",
        # store=True 
    )
    case_study = fields.Selection(
        string='Case Study',
        selection=[('continuous', 'Continuous'),
                   ('intermittent', 'Intermittent'),
                   ('graduate', 'Graduate')]
    )
    education_entity = fields.Selection(
        string='Education Entity',
        selection=[('governmental', 'Governmental'),
                   ('governmental_paid', 'Governmental/Paid'),
                   ('special', 'Special')]
    )
    education_start_date = fields.Date(string='Education Start Date')
    education_end_date = fields.Date(string='Education End Date')

    educational_certificate = fields.Many2many(
        'ir.attachment',
        'rel_education_status_educational_certificate_attachment',
        'education_status_id',
        'attachment_id',
        string='Educational Certificate'
    )
    education_levels = fields.Many2one("education.level", string='Education Levels')
    entities = fields.Many2one("res.partner", string='Entity',
                               domain="[('education_level_ids', 'in', education_levels)]")
    education_period_id = fields.Many2one("education.period", string='Education Period', domain="['|', '|', ('education_level_ids', 'in', education_levels), ('education_level_ids', '=', False),'|',('education_entity_ids', 'in', entities), ('education_entity_ids', '=', False)]")
    classroom = fields.Many2one('education.classroom', string='Classroom',
                                domain="[('education_level_id', '=', education_levels)]")
    rate_type = fields.Selection([
        ('from_4', 'From 4'),
        ('from_5', 'From 5'),
        ('from_100', 'From 100'),
    ], string='Rate Type')
    degree = fields.Many2one('education.result', string='Degree', compute='_compute_percentage_rate_type', store=True)
    percentage = fields.Float(string="Percentage%")
    specialization_ids = fields.Many2one('specialization.specialization', string='Specialization')
    intermittent_reason_id = fields.Many2one('education.illiterate.reason', string='Intermittent Reason')
    intermittent_date = fields.Date(string='Intermittent Date')
    family_member_age = fields.Integer(string="Age At Level Beginning", compute='_compute_family_member_age',
                                       store=True)
    family_member_delay = fields.Boolean(string="Member Delay", compute='_compute_family_member_delay', store=True)
    delay_reason_id = fields.Many2one('education.delay.reason', string='Delay Reason')
    weak_course_ids = fields.One2many('weak.course', 'education_status_id')

    @api.depends('percentage', 'rate_type')
    def _compute_percentage_rate_type(self):
        for rec in self:
            rec.degree = False

            if rec.percentage and rec.rate_type:
                degree_rec = self.env['education.result'].search([
                    ('rate_type', '=', rec.rate_type),
                    ('min_degree', '<=', rec.percentage),
                    ('max_degree', '>=', rec.percentage),
                ], limit=1)

                rec.degree = degree_rec.id if degree_rec else False

    @api.depends(
        'mother_grant_benefit_id',
        'mother_grant_benefit_id.education_status',
        'replacement_grant_benefit_id',
        'replacement_grant_benefit_id.replacement_education_status',
        'family_member_id',
        'family_member_id.education_status',
    )
    def _compute_education_status(self):
        for record in self:
            record.education_status = record.mother_grant_benefit_id.education_status or \
                                      record.replacement_grant_benefit_id.replacement_education_status or \
                                      record.family_member_id.education_status

    @api.depends("case_study")
    def _compute_education_status_type(self):
        for rec in self:
            if rec.case_study:
                if rec.case_study == "continuous":
                    rec.education_status_type = "current"
                else:
                    rec.education_status_type = "previous"
            else:
                rec.education_status_type = False

    @api.depends("education_start_date", "family_member_id", "family_member_id.birth_date")
    def _compute_family_member_age(self):
        for rec in self:
            if rec.education_start_date and rec.family_member_id and rec.family_member_id.birth_date:
                day = datetime.strptime(str(rec.family_member_id.birth_date), DEFAULT_SERVER_DATE_FORMAT)
                age = rd(rec.education_start_date, day)
                rec.family_member_age = age.years
            else:
                rec.family_member_age = 0

    @api.depends("family_member_age", "education_levels", "education_levels.level_expected_age")
    def _compute_family_member_delay(self):
        for rec in self:
            if rec.family_member_age > 0 and rec.education_levels and rec.education_levels.level_expected_age > 0:
                if rec.family_member_age > rec.education_levels.level_expected_age:
                    rec.family_member_delay = True
                else:
                    rec.family_member_delay = False
            else:
                rec.family_member_delay = False

    @api.onchange('education_status_type')
    def _onchange_education_status_type(self):
        relation_id = self.mother_grant_benefit_id or \
                      self.replacement_grant_benefit_id or \
                      self.family_member_id
        if self.education_status_type == 'current' and relation_id:
            existing_current = self.search([
                ('education_status_type', '=', 'current'),
                '|', '|',
                ('mother_grant_benefit_id', '=', relation_id._origin.id),
                ('replacement_grant_benefit_id', '=', relation_id._origin.id),
                ('family_member_id', '=', relation_id._origin.id)
            ], limit=1)
            if existing_current:
                return {
                    "warning": {
                        'title': _('Current Education Status Already Exists'),
                        'message': _(
                            "There is already an education status marked as Current.\nIf you save this, %s will be marked as Previous!") % existing_current.name
                    }
                }

    @api.onchange('education_period_id', 'education_period_id.start_date', 'education_period_id.end_date')
    def _onchange_field_name(self):
        self.ensure_one()
        if self.education_period_id:
            if self.education_period_id.start_date:
                self.education_start_date = self.education_period_id.start_date
            if self.education_period_id.end_date:
                self.education_end_date = self.education_period_id.end_date

    @api.model
    def create(self, vals):
        # Determine the prefix based on the related field
        prefix = 'EDU/'
        relation_field = False

        if vals.get('mother_grant_benefit_id'):
            prefix = 'EDUM/'
            relation_field = 'mother_grant_benefit_id'
        elif vals.get('replacement_grant_benefit_id'):
            prefix = 'EDUR/'
            relation_field = 'replacement_grant_benefit_id'
        elif vals.get('family_member_id'):
            prefix = 'EDUF/'
            relation_field = 'family_member_id'

        # Build domain filter to count records for the same category
        domain = [('name', 'like', prefix)]
        if relation_field and vals.get(relation_field):
            domain.append((relation_field, '=', vals.get(relation_field)))

        # Get the count of existing records with the same prefix & relation ID
        existing_count = self.search_count(domain) + 1
        formatted_number = str(existing_count).zfill(4)  # Format as 4-digit number

        # Assign computed sequence name
        vals['name'] = f"{prefix}{formatted_number}"

        # Ensure only one 'current' education status exists
        relation_id = vals.get('mother_grant_benefit_id',
                               vals.get('replacement_grant_benefit_id', vals.get('family_member_id', False)))
        if not self.env.context.get('skip_current_check') and vals.get(
                'education_status_type') == 'current' and relation_id:
            existing_current = self.search([
                ('education_status_type', '=', 'current'),
                '|', '|',
                ('mother_grant_benefit_id', '=', relation_id),
                ('replacement_grant_benefit_id', '=', relation_id),
                ('family_member_id', '=', relation_id)
            ], limit=1)

            if existing_current:
                existing_current.education_status_type = 'previous'

        return super(EducationStatus, self).create(vals)
