import base64
import functools

from markupsafe import escape

from odoo import api, fields, models
from odoo.addons.xeno_leave.models.leave_email import _leave_type_font_color
from odoo.tools import file_open

# Testing-phase hardcoded recipients, per HR's explicit request (2026-08-07)
# -- swap for a proper Settings-configurable list (same pattern as
# xeno_leave's res.company.xeno_monthly_report_recipient_ids) once this
# moves past testing.
_TEST_RECIPIENTS = ["thinzar@xenoptics.com", "susu@xenoptics.com"]

# Real Xenoptics brand values (theme_vars.scss's own comment: "pulled from
# the live xenoptics.com CSS"), reused here so this email matches the same
# red/navy identity as the rest of the app instead of inventing new colors.
_BRAND_RED = "#EC1D23"
_BRAND_NAVY = "#142933"
# Darker red requested specifically for the attendance table's header row
# (susu, 2026-08-11) -- distinct from _BRAND_RED, which stays as the
# lighter brand red used everywhere else in this email (headline, wordmark,
# signature accents).
_TABLE_HEADER_RED = "#c00000"

_AWARD_URL = "https://xenoptics.com/2025/06/xenoptics-at-interop-winner-of-best-of-show/"
_DISCLAIMER_URL = "https://xenon.com.au/email-disclaimer-notice/"


@functools.lru_cache(maxsize=1)
def _xeno_logo_data_uri():
    """Base64 data URI, not a plain <img src="http://.../static/..."> URL --
    the Odoo server here only has a private LAN address (susu, HR staff
    routinely check this mail off the office network/VPN), so a hosted-URL
    image would just show a broken-image icon for them. Pre-shrunk to
    440x142 (xeno_hr_dashboard/static/src/img/xenoptics_logo.png) so the
    inlined payload stays small -- the original supplied logo was
    2499x806/162KB, way oversized for a ~220px-wide email header. Cached
    (module-level, process-lifetime) since this cron only sends once/day
    and the file never changes at runtime.
    """
    with file_open("xeno_hr_dashboard/static/src/img/xenoptics_logo.png", "rb") as f:
        return "data:image/png;base64," + base64.b64encode(f.read()).decode()


class XenoHrDashboardEmail(models.AbstractModel):
    _name = "xeno.hr.dashboard.email"
    _description = "Daily email of the HR Dashboard's own Employee Attendance Report table"

    @api.model
    def _cron_xeno_send_daily_attendance_email(self):
        """ir.cron is scheduled for 09:30 ICT (nextcall stored as 02:30 UTC,
        this server/container run in UTC); the working-day gate itself
        (skip weekends and company holidays) lives here rather than in the
        cron's own scheduling, same idiom as xeno_attendance's own
        weekend/holiday checks in get_month_report()."""
        today = fields.Date.context_today(self)
        if today.weekday() >= 5:
            return
        is_holiday = bool(self.env["resource.calendar.leaves"].sudo().search_count([
            ("resource_id", "=", False),
            ("date_from", "<=", "%s 23:59:59" % today),
            ("date_to", ">=", "%s 00:00:00" % today),
        ]))
        if is_holiday:
            return
        self._xeno_send_daily_attendance_email(today)

    def _xeno_send_daily_attendance_email(self, today):
        rows = self.env["xeno.hr.dashboard"].get_leave_attendance_rows(str(today))
        html = self._xeno_render_email_html(today, rows)
        self.env["mail.mail"].sudo().create({
            "subject": "Update of Today's staff attendance - %s" % today,
            "body_html": html,
            "email_to": ",".join(_TEST_RECIPIENTS),
            "auto_delete": True,
        }).send()

    def _xeno_render_email_html(self, today, rows):
        # Layout matches the reference design susu supplied (red table
        # header, leave type colored by its own font color instead of an
        # Approved/Pending pill, a greeting line, and a real HR signature
        # block) -- see hr_dashboard_email.py's own module docstring/
        # constants for where the brand colors and the two footer links
        # come from. _leave_type_font_color is xeno_leave's own helper
        # (leave_email.py), reused as-is rather than re-defining the same
        # AL/PL/SL/ML/UL color map a third time in this codebase.
        if rows:
            body_rows = []
            for i, r in enumerate(rows, 1):
                cells = "".join(
                    '<td style="padding:8px 12px;border-bottom:1px solid #edf0f2;">%s</td>' % escape(str(v))
                    for v in (i, r["name"], r["position"], r["department"])
                )
                leave_type_color = _leave_type_font_color(r["leave_type"])
                body_rows.append(
                    '<tr>%s'
                    '<td style="padding:8px 12px;border-bottom:1px solid #edf0f2;'
                    'color:%s;font-weight:600;">%s</td>'
                    '<td style="padding:8px 12px;border-bottom:1px solid #edf0f2;">%s</td>'
                    '<td style="padding:8px 12px;border-bottom:1px solid #edf0f2;">%s</td>'
                    '<td style="padding:8px 12px;border-bottom:1px solid #edf0f2;">%s</td>'
                    '</tr>'
                    % (cells, leave_type_color, escape(r["leave_type"]),
                       escape(r["total_leave_days"]), escape(r["leave_date"]),
                       escape(r["back_to_work_date"]))
                )
            table_body = "".join(body_rows)
        else:
            table_body = (
                '<tr><td colspan="8" style="padding:24px;text-align:center;color:#adb5bd;">'
                "No approved or pending leaves for this date.</td></tr>"
            )

        headers = ["No.", "Name", "Position", "Team", "Leave Type",
                   "Total Leave Days", "Leave Date", "Back to Work Date"]
        head_cells = "".join(
            '<th style="padding:8px 12px;text-align:center;background:%s;color:#fff;'
            'font-size:13px;">%s</th>' % (_TABLE_HEADER_RED, h)
            for h in headers
        )

        return """
<div style="max-width:900px;margin:0 auto;font-family:Arial,Helvetica,sans-serif;color:%(navy)s;">
  <table style="width:100%%;margin-bottom:20px;"><tr>
    <td style="font-size:14px;line-height:1.6;vertical-align:top;">
      Dear Team,<br/><br/>
      You are kindly requested to review today's staff attendance details:
    </td>
    <td style="text-align:right;white-space:nowrap;vertical-align:top;">
      <img src="%(logo)s" alt="Xenoptics" height="50" style="height:50px;width:auto;"/>
    </td>
  </tr></table>

  <h3 style="color:%(red)s;text-align:center;margin:0 0 14px;font-size:16px;">Employee Attendance Report</h3>

  <div style="overflow-x:auto;">
    <table style="width:100%%;border-collapse:collapse;font-size:13px;text-align:center;">
      <thead><tr>%(head_cells)s</tr></thead>
      <tbody>%(table_body)s</tbody>
    </table>
  </div>

  <div style="margin-top:28px;font-size:12px;color:%(navy)s;">
    <div style="font-weight:700;">Human Resource Department, XENOptics Ltd.</div>
    <div style="margin-top:4px;">
      <span style="color:%(red)s;font-weight:700;">M</span>&#160;+66&#160;52&#160;081406
      &#160;&#160;|&#160;&#160;
      <span style="color:%(red)s;font-weight:700;">E</span>&#160;
      <a href="mailto:hr@xenoptics.com" style="color:#3b7dec;">hr@xenoptics.com</a>
    </div>
    <div style="margin-top:14px;">
      <a href="%(award_url)s" style="color:%(navy)s;text-decoration:none;font-weight:700;">
        Winner Best of Show Award at Interop 2025
      </a>
    </div>
    <div style="margin-top:6px;font-style:italic;font-size:11px;">
      Read more: <a href="%(award_url)s">%(award_url)s</a>
    </div>
    <div style="margin-top:12px;">
      <a href="%(disclaimer_url)s" style="color:#3b7dec;">Email Disclaimer Notice</a>
    </div>
  </div>
</div>
""" % {
            "navy": _BRAND_NAVY,
            "red": _BRAND_RED,
            "logo": _xeno_logo_data_uri(),
            "head_cells": head_cells,
            "table_body": table_body,
            "award_url": _AWARD_URL,
            "disclaimer_url": _DISCLAIMER_URL,
        }
