from odoo import _, api, fields, models

# Generic "personal wish" email shell -- shared by birthday wishes (below)
# and xeno_leave's return-from-leave welcome back message, which calls
# hr.employee._xeno_render_wish_email_html() directly (xeno_leave already
# depends on xeno_theme_slate, so this is a safe reuse direction). Kept
# parameterized (title/message/emoji) rather than birthday-specific so
# both callers get the same branded look without duplicating markup.
_WISH_TEMPLATE = """
<div style="max-width:520px;margin:0 auto;font-family:Arial,Helvetica,sans-serif;color:#142933;border:1px solid #d8e1e4;">
  <div style="background:#142933;padding:14px 20px;">
    <div style="color:#fff;font-weight:700;font-size:16px;">XenOptics HR System</div>
  </div>
  <div style="padding:24px 20px;text-align:center;">
    <div style="font-size:32px;margin-bottom:8px;">%(emoji)s</div>
    <div style="font-size:20px;font-weight:700;margin-bottom:10px;">%(title)s</div>
    <div style="font-size:14px;line-height:1.6;color:#3f5964;">
      %(message)s
    </div>
  </div>
  <div style="background:#142933;color:#b7c7cc;text-align:center;padding:8px;font-size:11px;">
    XenOptics HR &middot; Do not reply
  </div>
</div>
"""


class HrEmployee(models.Model):
    _inherit = "hr.employee"

    def _xeno_render_wish_email_html(self, title, message, emoji="🎉"):
        """Shared branded email shell for one-off personal HR notices
        (birthday, return-from-leave welcome back, ...). title/message are
        plain text -- callers are responsible for escaping if they ever
        contain user-controlled input (today's callers only use fixed,
        code-authored strings, no employee-entered text)."""
        return _WISH_TEMPLATE % {"emoji": emoji, "title": title, "message": message}

    xeno_last_birthday_wish_year = fields.Integer(
        groups="hr.group_hr_user", copy=False,
        help="Guards the daily birthday-wish cron from posting/emailing "
             "more than once in the same year, if it's ever triggered twice.",
    )
    xeno_is_birthday_today = fields.Boolean(
        compute="_compute_xeno_is_birthday_today",
        help="True on the employee's own birthday (month+day match today). "
             "Deliberately NOT groups-restricted, unlike birthday itself -- "
             "this only exposes a yes/no fact about the logged-in "
             "employee's own record, never the actual date, so a regular "
             "employee can see it on their own landing page without "
             "needing hr.group_hr_user's access to birthday.",
    )

    def _compute_xeno_is_birthday_today(self):
        today = fields.Date.context_today(self)
        for employee in self:
            b = employee.sudo().birthday
            employee.xeno_is_birthday_today = bool(
                b and b.month == today.month and b.day == today.day)

    @api.model
    def _cron_xeno_send_birthday_wishes(self):
        """Daily: anyone whose birthday (month+day) is today gets a chatter
        note + email, once per year (guarded by
        xeno_last_birthday_wish_year). Same delivery pattern as
        xeno_leave's _cron_xeno_welcome_back_from_maternity."""
        today = fields.Date.context_today(self)
        employees = self.sudo().search([
            ("active", "=", True),
            ("birthday", "!=", False),
        ])
        due = employees.filtered(
            lambda e: e.birthday.month == today.month and e.birthday.day == today.day
            and e.xeno_last_birthday_wish_year != today.year)
        for employee in due:
            employee._xeno_send_birthday_wish()

    def _xeno_send_birthday_wish(self):
        self.ensure_one()
        today = fields.Date.context_today(self)
        self.message_post(body=_(
            "🎉 Happy Birthday, %(name)s! Wishing you a great day.",
            name=self.name))
        email = self.work_email or (self.user_id.email if self.user_id else False)
        if email:
            html = self._xeno_render_wish_email_html(
                title=_("Happy Birthday, %(name)s!", name=self.name),
                message=_("Wishing you a fantastic day and a wonderful year "
                          "ahead. From all of us at XenOptics -- enjoy your day!"),
                emoji="🎉🎂🎉",
            )
            self.env["mail.mail"].sudo().create({
                "subject": _("Happy Birthday, %(name)s!", name=self.name),
                "body_html": html,
                "email_to": email,
                "auto_delete": True,
            }).send()
        self.xeno_last_birthday_wish_year = today.year


class HrEmployeePublic(models.Model):
    # hr.employee.public is a SQL-view model (_auto=False) whose own
    # _check_private_fields() rejects ANY field not literally defined on
    # this model -- independent of whether the real hr.employee field has
    # a groups= restriction. A regular (non-HR) user's own-record reads go
    # through this delegate, so xeno_is_birthday_today needs a matching
    # related field here too, or every employee landing-page load breaks
    # with "not available for employee public profiles" (confirmed live).
    _inherit = "hr.employee.public"

    xeno_is_birthday_today = fields.Boolean(related="employee_id.xeno_is_birthday_today")

    # NOTE: category_ids (Employee Tags/Groups) is NOT mirrored here.
    # Unlike xeno_is_birthday_today above, category_ids carries a genuine
    # groups="hr.group_hr_user" restriction on the real hr.employee field
    # itself -- a related= proxy still hits that same restricted column, so
    # exposing it here would just trade one AccessError for another ("You
    # do not have enough rights to access the field category_ids"),
    # confirmed live. The actual fix is xeno.hr.announcement's
    # xeno_get_my_announcements() (announcement matching moved server-side,
    # sudo()'d, never sending category_ids to the client at all) -- see
    # hr_announcement.py.
