from odoo import _, api, fields, models
from odoo.exceptions import ValidationError


class XenoAttendanceAutoRule(models.Model):
    _name = "xeno.attendance.auto.rule"
    _description = (
        "Auto-fill attendance rule, ported from XENHR's AttendanceAutoRule: "
        "employees/departments exempt from daily scanning (e.g. remote "
        "staff, management) are shown Present instead of Absent on a "
        "working day with no scan at all."
    )
    _order = "department_id, employee_id"

    employee_id = fields.Many2one(
        "hr.employee", string="Employee (specific)",
        help="Applies only to this employee.")
    department_id = fields.Many2one(
        "hr.department", string="Department",
        help="Applies to every employee in this department.")
    active = fields.Boolean(default=True)
    note = fields.Char()

    @api.constrains("employee_id", "department_id")
    def _check_target(self):
        for rec in self:
            if not rec.employee_id and not rec.department_id:
                raise ValidationError(
                    _("Set either an Employee or a Department for this rule."))

    def name_get(self):
        out = []
        for rec in self:
            target = rec.employee_id.name or rec.department_id.name or "?"
            out.append((rec.id, _("%s (auto-fill)") % target))
        return out

    @api.model
    def get_auto_fill_codes(self):
        """xeno_employee_code strings currently covered by an active
        auto-fill rule (direct employee match, or via department) --
        XENHR's own 'ignore' rule type is validated in their API but never
        actually processed anywhere in that codebase (confirmed dead code
        in ProcessAttendanceAutoRules/AttendanceAutoRuleController), so
        only the real auto_fill behavior is ported here.
        """
        Employee = self.env["hr.employee"].sudo()
        rules = self.sudo().search([("active", "=", True)])
        codes = set(rules.filtered("employee_id").mapped("employee_id.xeno_employee_code"))
        dept_ids = rules.filtered("department_id").mapped("department_id").ids
        if dept_ids:
            codes |= set(Employee.search([("department_id", "in", dept_ids)])
                         .mapped("xeno_employee_code"))
        codes.discard(False)
        return codes
