from markupsafe import Markup

from odoo import _, fields, models

_POLICY_TYPES = [
    ("leave", "Leave"),
    ("attendance", "Attendance"),
    ("overtime", "Overtime"),
    ("payroll", "Payroll"),
    ("conduct", "Code of Conduct"),
    ("safety", "Health & Safety"),
    ("other", "Other"),
]


class XenoHrPolicy(models.Model):
    _name = "xeno.hr.policy"
    _description = "Company Policy"
    _inherit = ["mail.thread"]
    _order = "publish_date desc, name"

    name = fields.Char(required=True, tracking=True)
    body = fields.Html(string="Content", required=True, default="<p></p>")
    policy_type = fields.Selection(
        _POLICY_TYPES, string="Type", default="other", required=True, tracking=True)
    publish_date = fields.Date(default=fields.Date.context_today, required=True, tracking=True)
    active = fields.Boolean(default=True, string="Status", tracking=True)

    def action_create_announcement(self):
        """Opens a new Announcement pre-filled from this policy (title +
        content) -- HR still picks Target Audience and Send Email
        Notification themselves on that form, nothing is auto-sent here.
        default_source_policy_id lets xeno.hr.announcement's create()
        log it back on this policy's own chatter once actually saved."""
        self.ensure_one()
        return {
            "type": "ir.actions.act_window",
            "res_model": "xeno.hr.announcement",
            "views": [[False, "form"]],
            "target": "new",
            "context": {
                "default_name": self.name,
                "default_body": self.body,
                "default_source_policy_id": self.id,
            },
        }

    def _xeno_log_announcement_created(self, announcement):
        self.ensure_one()
        base_url = self.env["ir.config_parameter"].sudo().get_param("web.base.url")
        action_id = self.env.ref("xeno_theme_slate.action_xeno_hr_announcement").id
        url = "%s/odoo/action-%s/%s" % (base_url, action_id, announcement.id)
        # message_post()'s body renders as literal escaped text unless
        # it's markupsafe.Markup -- confirmed live that Markup(_(...))
        # alone still isn't enough (wrapping an already-fully-formatted
        # str in Markup() as a final step doesn't retroactively make its
        # embedded tags trusted, since Markup's OWN __new__ escapes plain
        # str input unless it's built via Markup's own % operator, which
        # is the actual mechanism that marks the template's literal tags
        # as trusted while still auto-escaping the interpolated values).
        template = Markup(_('Announcement created from this policy: <a href="%s">%s</a>'))
        self.message_post(body=template % (url, announcement.name))
