# -*- coding: utf-8 -*-
import logging

from odoo import api, fields, models

_logger = logging.getLogger(__name__)


class ProjectTask(models.Model):
    _inherit = 'project.task'
    _description = 'Task'

    overrun_50_sent = fields.Boolean(
        string='50% Overrun Email Sent',
        default=False,
        copy=False,
    )
    overrun_75_sent = fields.Boolean(
        string='75% Overrun Email Sent',
        default=False,
        copy=False,
    )
    overrun_100_sent = fields.Boolean(
        string='100% Overrun Email Sent',
        default=False,
        copy=False,
    )
    is_ticket = fields.Boolean(
        string='Is Ticket',
        default=False,
        help='Marks this task as a ticket container.',
    )
    ticket_project_id = fields.Many2one(
        comodel_name='project.project',
        string='Ticket Source Project',
        ondelete='set null',
        help='The project from which this ticket was generated.',
    )
    hours_progress = fields.Float(
        string='Hours Progress (%)',
        compute='_compute_hours_progress',
        store=True,
        help='Percentage of planned hours consumed (effective_hours / planned_hours * 100).',
    )

    # ------------------------------------------------------------------
    # Computed fields
    # ------------------------------------------------------------------

    @api.depends('effective_hours', 'allocated_hours')
    def _compute_hours_progress(self):
        for task in self:
            planned = task.allocated_hours
            if planned and planned > 0:
                task.hours_progress = (task.effective_hours / planned) * 100.0
            else:
                task.hours_progress = 0.0

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

    @api.model
    def _check_overrun_and_notify(self):
        """Daily cron: check hour overruns and send notification emails."""
        tasks = self.search([
            ('allocated_hours', '>', 0),
            ('stage_id.fold', '=', False),
        ])

        tmpl_50 = self.env.ref(
            'jb_timesheet.mail_template_overrun_50',
            raise_if_not_found=False,
        )
        tmpl_75 = self.env.ref(
            'jb_timesheet.mail_template_overrun_75',
            raise_if_not_found=False,
        )
        tmpl_100 = self.env.ref(
            'jb_timesheet.mail_template_overrun_100',
            raise_if_not_found=False,
        )

        for task in tasks:
            progress = task.hours_progress

            if progress >= 100.0 and not task.overrun_100_sent and tmpl_100:
                self._send_overrun_mail(task, tmpl_100)
                task.sudo().write({'overrun_100_sent': True})

            elif progress >= 75.0 and not task.overrun_75_sent and tmpl_75:
                self._send_overrun_mail(task, tmpl_75)
                task.sudo().write({'overrun_75_sent': True})

            elif progress >= 50.0 and not task.overrun_50_sent and tmpl_50:
                self._send_overrun_mail(task, tmpl_50)
                task.sudo().write({'overrun_50_sent': True})

    def _send_overrun_mail(self, task, template):
        """Send overrun notification mail for a task."""
        try:
            template.send_mail(task.id, force_send=True)
        except Exception as exc:
            _logger.error(
                'jb_timesheet: failed to send overrun mail for task %s: %s',
                task.name, exc,
            )
