# -*- coding: utf-8 -*-
import logging
from datetime import date, timedelta

from odoo import api, fields, models

_logger = logging.getLogger(__name__)


class HrEmployee(models.Model):
    _inherit = 'hr.employee'
    _description = 'Employee'

    eit_user_id = fields.Char(
        string='EIT User ID',
        help='External EIT system user identifier.',
    )
    target_hours = fields.Float(
        string='Monthly Target Hours',
        default=0.0,
        help='Target billable hours per month for this employee.',
    )
    include_in_office_target = fields.Boolean(
        string='Include in Office Target',
        default=True,
        help='Include this employee in office-wide target reporting.',
    )
    remind_count = fields.Integer(
        string='Reminder Count',
        default=0,
        readonly=True,
        groups='jb_timesheet.group_timesheet_manager',
        help='Number of timesheet reminders sent this month.',
    )

    # ------------------------------------------------------------------
    # Scheduled action helpers
    # ------------------------------------------------------------------

    @api.model
    def _send_timesheet_reminders(self):
        """Weekly cron: remind employees who have no timesheet entries
        in the current week (Mon–Sun). Increments remind_count."""
        today = date.today()
        # Monday of current week
        monday = today - timedelta(days=today.weekday())
        sunday = monday + timedelta(days=6)

        employees = self.search([('include_in_office_target', '=', True)])
        template = self.env.ref(
            'jb_timesheet.mail_template_timesheet_reminder',
            raise_if_not_found=False,
        )
        if not template:
            _logger.warning('jb_timesheet: reminder mail template not found.')
            return

        AnalyticLine = self.env['account.analytic.line']
        for employee in employees:
            if not employee.user_id:
                continue
            line_count = AnalyticLine.search_count([
                ('employee_id', '=', employee.id),
                ('date', '>=', monday),
                ('date', '<=', sunday),
            ])
            if line_count == 0:
                try:
                    template.send_mail(employee.id, force_send=True)
                except Exception as exc:
                    _logger.error(
                        'jb_timesheet: failed to send reminder to %s: %s',
                        employee.name, exc,
                    )
                employee.sudo().write({'remind_count': employee.remind_count + 1})

    @api.model
    def _reset_monthly_remind_count_if_last_day(self):
        """Daily cron helper: reset remind_count on the last day of the month."""
        today = date.today()
        # Last day = first day of next month minus one day
        if today.month == 12:
            next_month = today.replace(year=today.year + 1, month=1, day=1)
        else:
            next_month = today.replace(month=today.month + 1, day=1)
        last_day = next_month - timedelta(days=1)
        if today == last_day:
            self._reset_monthly_remind_count()

    @api.model
    def _reset_monthly_remind_count(self):
        """Reset remind_count to 0 for all employees."""
        self.search([]).sudo().write({'remind_count': 0})
