# Part of Odoo. See LICENSE file for full copyright and licensing details.

import logging
from ast import literal_eval
from collections import defaultdict, Counter
from datetime import date, datetime, timedelta

from dateutil.relativedelta import MO, relativedelta

from odoo import api, fields, models, _
from odoo.exceptions import AccessError
from odoo.fields import Domain
from odoo.tools import OrderedSet, is_html_empty
from odoo.tools.misc import clean_context, get_lang, groupby
from odoo.tools.translate import LazyTranslate
from odoo.addons.base.models.ir_attachment import condition_values
from odoo.addons.mail.tools.discuss import Store
from .mail_message import MAX_COMODELS_FOR_DOMAIN, _find_allowed_doc_ids, exists_in_cache

_logger = logging.getLogger(__name__)
_lt = LazyTranslate(__name__)

_logger = logging.getLogger(__name__)
SECURITY_FIELDS = ('res_model', 'res_id', 'user_id')


class MailActivity(models.Model):
    """ An actual activity to perform. Activities are linked to
    documents using res_id and res_model_id fields. Activities have a deadline
    that can be used in kanban view to display a status. Once done activities
    are unlinked and a message is posted. This message has a new activity_type_id
    field that indicates the activity linked to the message. """
    _name = 'mail.activity'
    _description = 'Activity'
    _order = 'date_deadline ASC, id ASC'
    _rec_name = 'summary'
    _access_domain_heavy = True

    @api.model
    def default_get(self, fields):
        res = super().default_get(fields)
        if 'res_model_id' in fields and res.get('res_model'):
            res['res_model_id'] = self.env['ir.model']._get(res['res_model']).id
        return res

    @api.model
    def _default_activity_type(self):
        default_vals = self.default_get(['res_model_id', 'res_model'])
        current_model = default_vals.get('res_model')
        if default_vals.get('res_model_id'):
            current_model = self.env["ir.model"].sudo().browse(default_vals['res_model_id']).model
        return self._default_activity_type_for_model(current_model)

    @api.model
    def _default_activity_type_for_model(self, model):
        """ Take first one found, ordered by sequence. Keep it simple. """
        if model:
            return self.env['mail.activity.type'].search(['|', ('res_model', '=', model), ('res_model', '=', False)], limit=1)
        return self.env['mail.activity.type'].search([('res_model', '=', False)], limit=1)

    # owner
    res_model_id = fields.Many2one(
        'ir.model', 'Document Model',
        index=True, ondelete='cascade', required=False)
    res_model = fields.Char(
        'Related Document Model',
        index=True, related='res_model_id.model', precompute=True, store=True, readonly=True)
    res_id = fields.Many2oneReference(string='Related Document ID', index=True, model_field='res_model')
    res_name = fields.Char(
        'Document Name', compute='_compute_res_name', compute_sudo=True, store=True,
        readonly=True)
    # activity
    activity_type_id = fields.Many2one(
        'mail.activity.type', string='Activity Type',
        domain="['|', ('res_model', '=', False), ('res_model', '=', res_model)]", ondelete='restrict',
        default=_default_activity_type)
    activity_category = fields.Selection(related='activity_type_id.category', readonly=True)
    activity_decoration = fields.Selection(related='activity_type_id.decoration_type', readonly=True)
    icon = fields.Char('Icon', related='activity_type_id.icon', readonly=True)
    activity_plan_id = fields.Many2one('mail.activity.plan', string='Plan', ondelete='set null', copy=False)
    activity_template_id = fields.Many2one('mail.activity.plan.template', string='Generated From',
                                           index='btree_not_null')
    summary = fields.Char('Summary')
    note = fields.Html('Note', sanitize_style=True)
    date_deadline = fields.Date('Due Date', index=True, required=True, default=fields.Date.context_today)
    date_done = fields.Date('Done Date', compute='_compute_date_done', store=True)
    feedback = fields.Text('Feedback')
    automated = fields.Boolean(
        'Automated activity', readonly=True,
        help='Indicates this activity has been created automatically and not by any user.')
    technical_usage = fields.Selection(selection=[('none', 'Non Technical')], default='none', readonly=True, help="Technical identifier")
    # Attachments are linked to a document through model / res_id and to the activity through this field.
    attachment_ids = fields.Many2many(
        'ir.attachment', 'activity_attachment_rel',
        'activity_id', 'attachment_id',
        string='Attachments',
        bypass_search_access=True,
    )
    # description
    user_id = fields.Many2one(
        'res.users', 'Assigned to',
        index=True, required=False, ondelete='cascade')
    user_tz = fields.Selection(string='Timezone', related="user_id.tz", store=True)
    state = fields.Selection([
        ('overdue', 'Overdue'),
        ('today', 'Today'),
        ('planned', 'Planned'),
        ('done', 'Done')], 'State',
        compute='_compute_state')
    mail_template_ids = fields.Many2many(related='activity_type_id.mail_template_ids', readonly=True)
    # access
    can_write = fields.Boolean(compute='_compute_can_write') # used to hide buttons if the current user has no access
    active = fields.Boolean(default=True)

    # if model: valid res_id
    _check_res_id_is_set_if_model = models.Constraint(
        """CHECK(
            (COALESCE(res_model, '') <> '' AND (res_id IS NOT NULL AND res_id != 0)) OR
            (COALESCE(res_model, '') = '' AND (res_id IS NULL OR res_id = 0))
        )""",
        'Activities have to be linked to records with a not null res_id.',
    )
    # if no model: user_id is required (no floating activities noone can see)
    _check_user_id_is_set_if_model = models.Constraint(
        """CHECK(
            (COALESCE(res_model, '') <> '' OR user_id IS NOT NULL)
        )""",
        'Activities must be assigned if not attached to a document.',
    )

    @api.depends('active')
    def _compute_date_done(self):
        unarchived = self.filtered('active')
        unarchived.date_done = False
        # keep earliest archive date if multi archive
        toupdate = (self - unarchived).filtered(lambda act: not act.date_done)
        toupdate.date_done = fields.Datetime.now()

    @api.depends('res_model', 'res_id')
    def _compute_res_name(self):
        free = self.filtered(lambda a: not a.res_model or not a.res_id)
        free.res_name = False
        for activity in (self - free):
            activity.res_name = activity.res_model and \
                self.env[activity.res_model].browse(activity.res_id).display_name

    @api.depends('active', 'date_deadline')
    def _compute_state(self):
        for record in self.filtered(lambda activity: activity.date_deadline):
            tz = record.user_tz
            date_deadline = record.date_deadline
            record.state = 'done' if not record.active else self._compute_state_from_date(date_deadline, tz)

    @api.model
    def _compute_state_from_date(self, date_deadline, tz=False):
        date_deadline = fields.Date.to_date(date_deadline)
        if tz:
            today = fields.Date.context_today(self.with_context(tz=tz))
        else:
            today = fields.Date.today()
        diff = (date_deadline - today)
        if diff.days == 0:
            return 'today'
        elif diff.days < 0:
            return 'overdue'
        else:
            return 'planned'

    @api.depends('res_model', 'res_id', 'user_id')
    def _compute_can_write(self):
        valid_records = self._filtered_access('write')
        for record in self:
            record.can_write = record in valid_records

    @api.onchange('activity_type_id')
    def _onchange_activity_type_id(self):
        if self.activity_type_id:
            if self.activity_type_id.summary:
                self.summary = self.activity_type_id.summary
            self.date_deadline = self.activity_type_id._get_date_deadline()
            self.user_id = self.activity_type_id.default_user_id or self.env.user
            if self.activity_type_id.default_note:
                self.note = self.activity_type_id.default_note

    def _check_access(self, operation: str) -> tuple | None:
        """ Determine the subset of ``self`` for which ``operation`` is allowed.
        A custom implementation is done on activities as this document has some
        access rules and is based on related document for activities that are
        not covered by those rules.

        Access on activities are the following :

          * read: access rule AND (assigned to user OR read rights on related documents);
          * write: access rule OR (``mail_post_access`` or write) rights on related documents);
          * create: access rule AND (``mail_post_access`` or write) right on related documents;
          * unlink: access rule OR (``mail_post_access`` or write) rights on related documents);
        """
        result = super()._check_access(operation)
        if not self:
            return result

        # determine activities on which to check the related document
        if operation == 'read':
            # check activities allowed by access rules
            activities = self - result[0] if result else self
            activities -= activities.sudo().filtered_domain([('user_id', '=', self.env.uid)])
        elif operation == 'create':
            # check activities allowed by access rules
            activities = self - result[0] if result else self
        else:
            assert operation in ('write', 'unlink'), f"Unexpected operation {operation!r}"
            # check access to the model, and check the forbidden records only
            if self.browse()._check_access(operation):
                return result
            activities = result[0] if result else self.browse()
            result = None

        if not activities:
            return result

        # now check access on related document of 'activities', and collect the
        # ids of forbidden activities; free activities are checked against user_id
        model_docid_actids = defaultdict(lambda: defaultdict(list))
        forbidden_ids = []
        for activity in activities.sudo():
            if activity.res_model and activity.res_id:
                model_docid_actids[activity.res_model][activity.res_id].append(activity.id)
            elif activity.user_id.id != self.env.uid:
                forbidden_ids.append(activity.id)

        allowed = _find_allowed_doc_ids(self.env, model_docid_actids, operation)
        forbidden_ids.extend(
            act_id
            for docid_actids in model_docid_actids.values()
            for act_ids in docid_actids.values()
            for act_id in act_ids
            if act_id not in allowed
        )

        if forbidden_ids:
            forbidden = self.browse(forbidden_ids)
            if result:
                result = (result[0] + forbidden, result[1])
            else:
                result = (forbidden, lambda: forbidden._make_access_error(operation))
            forbidden.invalidate_recordset()  # avoid cache pollution

        return result

    def _make_access_error(self, operation: str) -> AccessError:
        return AccessError(_(
            "The requested operation cannot be completed due to security restrictions. "
            "Please contact your system administrator.\n\n"
            "(Document type: %(type)s, Operation: %(operation)s)\n\n"
            "Records: %(records)s, User: %(user)s",
            type=self._description,
            operation=operation,
            records=self.ids[:6],
            user=self.env.uid,
        ))

    # ------------------------------------------------------
    # ORM overrides
    # ------------------------------------------------------

    @api.model_create_multi
    def create(self, vals_list):
        activities = super(MailActivity, self).create(vals_list)

        # find partners related to responsible users, separate readable from unreadable
        if any(user != self.env.user for user in activities.user_id):
            user_partners = activities.user_id.partner_id
            readable_user_partners = user_partners._filtered_access('read')
        else:
            readable_user_partners = self.env.user.partner_id

        # when creating activities for other: send a notification to assigned user;
        if self.env.context.get('mail_activity_quick_update'):
            activities_to_notify = self.env['mail.activity']
        else:
            activities_to_notify = activities.filtered(lambda act: act.user_id != self.env.user)
        if activities_to_notify:
            to_sudo = activities_to_notify.filtered(lambda act: act.user_id.partner_id not in readable_user_partners)
            other = activities_to_notify - to_sudo
            to_sudo.sudo().action_notify()
            other.action_notify()

        # subscribe (batch by model and user to speedup)
        for model, activity_data in activities.filtered('res_model')._classify_by_model().items():
            per_user = defaultdict(set)
            for activity in activity_data['activities'].filtered(lambda act: act.user_id):
                per_user[activity.user_id].add(activity.res_id)
            for user, res_ids in per_user.items():
                pids = user.partner_id.ids if user.partner_id in readable_user_partners else user.sudo().partner_id.ids
                self.env[model].browse(res_ids).message_subscribe(partner_ids=pids)

        # send notifications about activity creation
        todo_activities = activities.filtered(lambda act: act.active and act.date_deadline <= fields.Date.today() and act.user_id)
        if todo_activities:
            for user, user_activities in todo_activities.grouped('user_id').items():
                user._bus_send("mail.activity/updated", {"activity_created": True, "count_diff": len(user_activities)})
        return activities

    def write(self, vals):
        today = fields.Date.today()

        def get_user_todo_activity_count(activities):
            return {
                user: len(user_activities.filtered(lambda a: a.active and a.date_deadline <= today))
                for user, user_activities in activities.grouped('user_id').items()
                if user
            }

        original_user_todo_activity_count = None
        if 'date_deadline' in vals or 'active' in vals or 'user_id' in vals:
            original_user_todo_activity_count = get_user_todo_activity_count(self)

        new_user_activities = self.env['mail.activity']
        if vals.get('user_id'):
            new_user_activities = self.filtered(lambda activity: activity.user_id.id != vals.get('user_id'))

        res = super().write(vals)

        # notify new responsibles
        if vals.get('user_id'):
            if vals['user_id'] != self.env.uid:
                if not self.env.context.get('mail_activity_quick_update', False):
                    new_user_activities.action_notify()
            new_user = self.env['res.users'].browse(vals['user_id'])
            for res_model, model_activities in new_user_activities.filtered(
                lambda activity: activity.res_model and activity.res_id
            ).grouped('res_model').items():
                res_ids = OrderedSet(id_ for id_ in model_activities.mapped('res_id') if id_)
                self.env[res_model].browse(res_ids).message_subscribe(partner_ids=new_user.partner_id.ids)

        # update activity counter
        if original_user_todo_activity_count is not None:
            new_user_todo_activity_count = get_user_todo_activity_count(self)
            for user in new_user_todo_activity_count.keys() | original_user_todo_activity_count.keys():
                count_diff = new_user_todo_activity_count.get(user, 0) - original_user_todo_activity_count.get(user, 0)
                if count_diff > 0:
                    user._bus_send("mail.activity/updated", {"activity_created": True, "count_diff": count_diff})
                elif count_diff < 0:
                    user._bus_send("mail.activity/updated", {"activity_deleted": True, "count_diff": count_diff})

        return res

    def unlink(self):
        todo_activities = self.filtered(lambda act: act.active and act.date_deadline <= fields.Date.today() and act.user_id)
        if todo_activities:
            for user, user_activities in todo_activities.grouped('user_id').items():
                user._bus_send("mail.activity/updated", {"activity_deleted": True, "count_diff": -len(user_activities)})
        return super().unlink()

    @api.model
    def _search(self, domain, offset=0, limit=None, order=None, *, bypass_access=False, **kwargs):
        """Implement custom access rules and `active_test` behavior.

        This method enhances the standard search in two ways:

        1.  **Archived Records Search**: If the search domain includes a filter on
            the 'Done Date' (`date_done`) field, the search automatically includes
            archived records (`active_test=False`). This allows users to find
            past activities that have been completed and subsequently archived.

        2.  **Custom Access Rights**: It filters search results to only include
            activities the current user is allowed to see. An activity is
            accessible if the user is the assignee (`user_id`), or if they have
            read access to the related document (`res_model`, `res_id`). This
            logic is detailed in :meth:`~._check_access`.
            Superusers bypass this and perform a standard search.
        """
        domain = Domain(domain).optimize(self)

        if any(
            condition.field_expr == 'date_done' and condition.value
            for condition in domain.iter_conditions()
        ):
            kwargs['active_test'] = False

        # Rules do not apply to administrator or when we search only activities assigned to the current user
        domain = Domain(domain).optimize(self)
        if self.env.su or bypass_access or domain.is_false() or tuple(condition_values(self, 'user_id', domain) or ()) == (self.env.uid,):
            return super()._search(domain, offset, limit, order, bypass_access=bypass_access, **kwargs)
        if self.env.context.get('_generating_sql_for_fields'):
            raise ValueError("Cannot generate SQL for whole mail.activity")

        # search by ids
        if (ids := condition_values(self, 'id', domain)) is not None:
            if (not order or order[:2] == 'id') and domain.map_conditions(lambda d: Domain.TRUE if d.field_expr == 'id' and d.operator == 'in' else d).is_true():
                # trivial domain, can skip search, in most cases check access removes inexisting records
                records = exists_in_cache(self.browse(ids), hint_field='res_model')
                records = records._filtered_access('read')
                if order:
                    records = records.sorted(order)
            else:
                records = self.browse(super()._search(domain, order=order, **kwargs))
                records = records._filtered_access('read')
            if offset > 0:
                records = records[offset:]
            if limit is not None:
                records = records[:limit]
            return records._as_query(ordered=bool(order))

        # searching for all messages or a subset of models
        res_model_names = condition_values(self, 'res_model', domain) or ()
        if not (0 < len(res_model_names) <= MAX_COMODELS_FOR_DOMAIN):
            query = super()._search(domain, offset, limit, order, **kwargs)
            records = self._fetch_query(query, [self._fields[f] for f in SECURITY_FIELDS])
            return records._filtered_access('read')._as_query(ordered=bool(order))

        # search by model and res_id
        sec_domain = Domain('user_id', '=', self.env.uid)
        env = self.with_context(active_test=False).env
        for res_model_name in res_model_names:
            if res_model_name not in env:
                continue
            comodel = env[res_model_name]
            codomain = Domain('res_model', '=', comodel._name)
            comodel_res_ids = condition_values(self, 'res_id', domain.map_conditions(
                lambda cond: codomain & cond if cond.field_expr == 'res_model' else cond
            ))
            # similar implementation to what is in mail.message._search
            comodel_domain = Domain.FALSE
            comodel_domain_remaining = Domain.TRUE
            for domain_operation, doc_operation in comodel._mail_get_operation_for_mail_message_operation('read'):
                domain_operation, comodel_domain_remaining = (
                    comodel_domain_remaining & domain_operation,
                    comodel_domain_remaining & ~domain_operation,
                )
                if not comodel.has_access(doc_operation):
                    continue
                if doc_operation == 'read':
                    comodel_rule = Domain.TRUE  # covered by the search below
                else:
                    comodel_rule = self.env['ir.rule']._compute_domain(comodel._name, doc_operation)
                comodel_domain |= (domain_operation & comodel_rule)
            if comodel_res_ids is not None:
                comodel_domain &= Domain('id', 'in', comodel_res_ids)
            comodel_domain = comodel_domain.optimize_full(comodel.sudo())
            query = comodel._search(comodel_domain)
            if query.is_empty():
                continue
            if query.where_clause:
                codomain &= Domain('res_id', 'any!', query)
            sec_domain |= codomain

        return super()._search(domain & sec_domain, offset, limit, order, **kwargs)

    @api.depends('summary', 'activity_type_id')
    def _compute_display_name(self):
        for record in self:
            name = record.summary or record.activity_type_id.display_name
            record.display_name = name

    # ------------------------------------------------------
    # Business Methods
    # ------------------------------------------------------

    def action_notify(self):
        classified = self._classify_by_model()
        for model, activity_data in classified.items():
            records_sudo = self.env[model].sudo().browse(activity_data['record_ids'])
            activity_data['record_ids'] = records_sudo.exists().ids  # in case record was cascade-deleted in DB, skipping unlink override

        for activity in self.filtered('res_model'):
            if activity.res_id not in classified[activity.res_model]['record_ids']:
                continue

            if activity.user_id.lang:
                # Send the notification in the assigned user's language
                activity = activity.with_context(lang=activity.user_id.lang)

            model_description = activity.env['ir.model']._get(activity.res_model).display_name
            body = activity.env['ir.qweb']._render(
                'mail.message_activity_assigned',
                {
                    'activity': activity,
                    'model_description': model_description,
                    'is_html_empty': is_html_empty,
                },
                minimal_qcontext=True
            )
            record = activity.env[activity.res_model].browse(activity.res_id)
            if activity.user_id:
                record.with_context(
                    email_notification_force_header=True,
                    email_notification_force_footer=True,
                ).message_notify(
                    partner_ids=activity.user_id.partner_id.ids,
                    body=body,
                    model_description=model_description,
                    email_layout_xmlid='mail.mail_notification_layout',
                    subject=_('"%(activity_name)s: %(summary)s" assigned to you',
                              activity_name=activity.res_name,
                              summary=activity.summary or activity.activity_type_id.name or ''),
                    subtitles=[
                        _lt('Activity: %s', activity.activity_type_id.name) if activity.activity_type_id.name
                        else _lt('Activity: Todo'),
                        _lt('Deadline: %s', activity.date_deadline.strftime(get_lang(activity.env).date_format))],
                )

    def action_done(self):
        """ Wrapper without feedback because web button add context as
        parameter, therefore setting context to feedback """
        return self.filtered(lambda r: r.active).action_feedback()

    def action_done_redirect_to_other(self):
        """ Mark activity as done and return action mail.mail_activity_without_access_action.

        Goal: Unless "keep done" activity is enabled, when marking an activity as done,
        the activity is deleted and can no more be displayed. To overcome this, we return
        an action that will launch the list view displaying the activities corresponding
        to the active_ids from the context (i.e.: the remaining "other activities"). If the
        right context is not available, we recompute the activities to display.
        """
        self.action_done()
        action = self.env["ir.actions.actions"]._for_xml_id('mail.mail_activity_without_access_action')
        action_context = literal_eval(action.get('context', '{}'))
        if self.env.context.get('active_model') == 'mail.activity':
            active_ids = self.env.context.get('active_ids', [])
        else:
            # Wrong context -> we recompute the activities for which the user has no access to the underlying record
            activity_groups = self.env['res.users']._get_activity_groups()
            activity_model_id = self.env['ir.model']._get_id('mail.activity')
            active_ids = next((g['activity_ids'] for g in activity_groups if g['id'] == activity_model_id), [])
        action['context'] = {
            **action_context,
            'active_ids': active_ids,
            'active_model': 'mail.activity',
        }
        return action

    def action_feedback(self, feedback=False, attachment_ids=None):
        messages = self.with_context(
            clean_context(self.env.context)
        )._action_done(feedback=feedback, attachment_ids=attachment_ids)
        return messages[0].id if messages else False

    def action_done_schedule_next(self):
        """ Wrapper without feedback because web button add context as
        parameter, therefore setting context to feedback """
        return self.action_feedback_schedule_next()

    def action_feedback_schedule_next(self, feedback=False, attachment_ids=None):
        ctx = dict(
            clean_context(self.env.context),
            activity_previous_deadline=self.date_deadline,
            active_id=self.res_id,
            active_model=self.res_model,
        )
        # Only set if suggested; sending False disables compute fallback
        if self.activity_type_id.suggested_next_type_id:
            ctx['default_activity_type_id'] = self.activity_type_id.suggested_next_type_id.id
        self._action_done(feedback=feedback, attachment_ids=attachment_ids)  # will unlink activity, dont access self after that
        return {
            'name': _('Schedule Activity'),
            'context': ctx,
            'view_mode': 'form',
            'res_model': 'mail.activity.schedule',
            'views': [(False, 'form')],
            'type': 'ir.actions.act_window',
            'target': 'new',
        }

    def _action_done(self, feedback=False, attachment_ids=None):
        """ Private implementation of marking activity as done: posting a message and
            archiving activity (since done).
            :param feedback: optional feedback from user when marking activity as done
            :param attachment_ids: list of ir.attachment ids to attach to the posted mail.message
            :returns: recordset of posted mail.message
        """
        # marking as 'done'
        messages = self.env['mail.message']
        ongoing_activities = self.filtered(lambda a: not a.date_done)

        # Search for all attachments linked to the activities we are about to archive. This way, we
        # can link them to the message posted and prevent their disparition. The move is done in
        # sudo to avoid losing inaccessible attachments.
        activity_attachments = self.env['ir.attachment'].sudo().search_fetch([
            ('res_model', '=', self._name),
            ('res_id', 'in', self.ids),
        ], ['res_id']).grouped('res_id')
        attachments_to_remove = self.env['ir.attachment']
        activities_to_remove = self.browse()

        for model, activity_data in ongoing_activities.filtered('res_model')._classify_by_model().items():
            # Allow user without access to the record to "mark as done" activities assigned to them. At the end of the
            # method, the activity is archived which ensure the user has enough right on the activities.
            records_sudo = self.env[model].sudo().browse(activity_data['record_ids'])
            existing = records_sudo.exists()  # in case record was cascade-deleted in DB, skipping unlink override
            for record_sudo, activity in zip(records_sudo, activity_data['activities']):

                # post message on activity, before deleting it
                if record_sudo in existing:
                    activity_message = record_sudo.message_post_with_source(
                        'mail.message_activity_done',
                        attachment_ids=attachment_ids,
                        author_id=self.env.user.partner_id.id,
                        render_values={
                            'activity': activity,
                            'feedback': feedback,
                            'display_assignee': activity.user_id != self.env.user
                        },
                        mail_activity_type_id=activity.activity_type_id.id,
                        subtype_xmlid='mail.mt_activities',
                    )
                else:
                    activity_message = self.env['mail.message']
                    activities_to_remove += activity

                message_attachments = activity_attachments.get(activity.id) or self.env['ir.attachment']
                attachment_ids = (attachment_ids or []) + message_attachments.ids
                if attachment_ids:
                    activity.attachment_ids = attachment_ids

                # Moving the attachments in the message
                # TODO: Fix void res_id on attachment when you create an activity with an image
                # directly, see route /web_editor/attachment/add
                message_attachments = activity_attachments.get(activity.id)
                if message_attachments and activity_message:
                    message_attachments.write({
                        'res_id': activity_message.id,
                        'res_model': activity_message._name,
                    })
                    activity_message.attachment_ids = message_attachments.ids
                # removing attachments linked to activity if record is missing
                elif message_attachments:
                    attachments_to_remove += message_attachments
                messages += activity_message

        # remove lost activities and attachments, not actionnable anyway anymore
        if attachments_to_remove:
            attachments_to_remove.unlink()
        if activities_to_remove:
            activities_to_remove.unlink()

        # once done, archive to keep history without keeping them alive
        (self - activities_to_remove).action_archive()
        if feedback:
            (self - activities_to_remove).feedback = feedback
        return messages

    @api.readonly
    def action_close_dialog(self):
        return {'type': 'ir.actions.act_window_close'}

    @api.readonly
    def action_open_document(self):
        """ Opens the related record based on the model and ID, or activity if user has no
         access to the related record."""
        self.ensure_one()
        if not self.res_model:
            view_id = self.env.ref('mail.mail_activity_view_form_popup').id
            return {
                'res_id': self.id,
                'type': 'ir.actions.act_window',
                'view_mode': 'form',
                'res_model': 'mail.activity',
                'view_id': view_id,
                'views': [(view_id, 'form')],
                'target': 'new',
            }
        if not self.env[self.res_model].browse(self.res_id).has_access('read'):
            return {
                'res_id': self.id,
                'res_model': 'mail.activity',
                'target': 'current',
                'type': 'ir.actions.act_window',
                'view_mode': 'form',
                'views': [(self.env.ref('mail.mail_activity_view_form_without_record_access').id, 'form')],
            }
        return {
            'res_id': self.res_id,
            'res_model': self.res_model,
            'target': 'current',
            'type': 'ir.actions.act_window',
            'view_mode': 'form',
            'views': [(False, 'form')],
        }

    def action_reschedule_today(self):
        self.filtered('active').date_deadline = date.today()

    def action_reschedule_tomorrow(self):
        self.filtered('active').date_deadline = date.today() + timedelta(days=1)

    def action_reschedule_nextweek(self):
        self.filtered('active').date_deadline = date.today() + relativedelta(weeks=1, weekday=MO(-1))

    def action_cancel(self):
        for activity in self:
            if activity.active:
                activity.unlink()

    @api.readonly
    def activity_format(self):
        return Store().add(self, "_store_activity_fields").get_result()

    def _store_activity_fields(self, res: Store.FieldList):
        res.attr("activity_category")
        res.one("activity_type_id", ["name"])
        res.extend(["can_write", "create_date"])
        res.one("create_uid", lambda res: res.one("partner_id", ["name"]))
        res.extend(["date_deadline", "date_done", "display_name", "icon", "note"])
        res.extend(["res_id", "res_model", "state", "summary"])
        res.one("user_id", lambda res: res.one("partner_id", "_store_partner_fields"))
        res.many("attachment_ids", ["name"])
        res.many("mail_template_ids", ["name"])

    @api.readonly
    @api.model
    def get_activity_data(self, res_model, domain, limit=None, offset=0, fetch_done=False):
        """ Get aggregate data about records and their activities.

        The goal is to fetch and compute aggregated data about records and their
        activities to display them in the activity views and the chatter. For example,
        the activity view displays it as a table with columns and rows being respectively
        the activity_types and the activity_res_ids, and the grouped_activities being the
        table entries with the aggregated data.

        :param str res_model: model of the records to fetch
        :param list domain: record search domain
        :param int limit: maximum number of records to fetch
        :param int offset: offset of the first record to fetch
        :param bool fetch_done: determines if "done" activities are integrated in the
            aggregated data or not.
        :returns: {'activity_types': dict of activity type info
                            {id: int, name: str, mail_template: list of {id:int, name:str}}
                       'activity_res_ids': list<int> of record id ordered by closest date
                            (deadline for ongoing activities, and done date for done activities)
                       'grouped_activities': dict<dict>
                            res_id -> activity_type_id -> aggregated info as:
                                count_by_state dict: mapping state to count (ex.: 'planned': 2)
                                ids list: activity ids for the res_id and activity_type_id
                                reporting_date str: aggregated date of the related activities as
                                    oldest deadline of ongoing activities if there are any
                                    or most recent date done of completed activities
                                state dict: aggregated state of the related activities
                                user_assigned_ids list: activity responsible id ordered
                                    by closest deadline of the related activities
                                attachments_info: dict with information about the attachments
                                    {'count': int, 'most_recent_id': int, 'most_recent_name': str}
                       }
        :rtype: dict
        """
        user_tz = self.user_id.sudo().tz
        DocModel = self.env[res_model]
        Activity = self.env['mail.activity']

        # 1. Retrieve all ongoing and completed activities according to the parameters
        activity_types = self.env['mail.activity.type'].search([('res_model', 'in', (res_model, False))])
        activity_domain = [('res_model', '=', res_model)]
        is_filtered = domain or limit or offset
        if is_filtered:
            activity_domain.append(('res_id', 'in', DocModel._search(domain or [], offset, limit, DocModel._order) if is_filtered else []))
        all_activities = Activity.with_context(active_test=not fetch_done).search(
            activity_domain, order='date_done DESC, date_deadline ASC')
        all_ongoing = all_activities.filtered('active')
        all_completed = all_activities.filtered(lambda act: not act.active)

        # 2. Get attachment of completed activities
        if all_completed:
            attachment_ids = all_completed.attachment_ids.ids
            attachments_by_id = {
                a['id']: a
                for a in self.env['ir.attachment'].search_read([['id', 'in', attachment_ids]], ['create_date', 'name'])
            } if attachment_ids else {}
        else:
            attachments_by_id = {}

        # 3. Group activities per records and activity type
        grouped_completed = {group: Activity.browse([v.id for v in values])
                             for group, values in groupby(all_completed, key=lambda a: (a.res_id, a.activity_type_id))}
        grouped_ongoing = {group: Activity.browse([v.id for v in values])
                           for group, values in groupby(all_ongoing, key=lambda a: (a.res_id, a.activity_type_id))}

        # 4. Filter out unreadable records
        res_id_type_tuples = grouped_ongoing.keys() | grouped_completed.keys()
        if not is_filtered:
            filtered = set(DocModel.search([('id', 'in', [r[0] for r in res_id_type_tuples])]).ids)
            res_id_type_tuples = list(filter(lambda r: r[0] in filtered, res_id_type_tuples))

        # 5. Format data
        res_id_to_date_done = {}
        res_id_to_deadline = {}
        grouped_activities = defaultdict(dict)
        for res_id_tuple in res_id_type_tuples:
            res_id, activity_type_id = res_id_tuple
            ongoing = grouped_ongoing.get(res_id_tuple, Activity)
            completed = grouped_completed.get(res_id_tuple, Activity)
            activities = ongoing | completed

            # As completed is sorted on date_done DESC, we take here the max date_done
            date_done = completed and completed[0].date_done
            # As ongoing is sorted on date_deadline ASC, we take here the min date_deadline
            date_deadline = ongoing and ongoing[0].date_deadline
            if date_deadline and (res_id not in res_id_to_deadline or date_deadline < res_id_to_deadline[res_id]):
                res_id_to_deadline[res_id] = date_deadline
            if date_done and (res_id not in res_id_to_date_done or date_done > res_id_to_date_done[res_id]):
                res_id_to_date_done[res_id] = date_done
            # As ongoing is sorted on date_deadline, we get assignees on activity with oldest deadline first
            user_assigned_ids = ongoing.user_id.ids
            attachments = [attachments_by_id[attach.id] for attach in completed.attachment_ids]

            grouped_activities[res_id][activity_type_id.id] = {
                'count_by_state': dict(Counter(
                    self._compute_state_from_date(act.date_deadline, user_tz) if act.active else 'done'
                    for act in activities)),
                'ids': activities.ids,
                'reporting_date': ongoing and date_deadline or date_done or None,
                'state': self._compute_state_from_date(date_deadline, user_tz) if ongoing else 'done',
                'user_assigned_ids': user_assigned_ids,
                'summaries': [act.summary if act.summary else '' for act in activities],
            }
            if attachments:
                most_recent_attachment = max(attachments, key=lambda a: (a['create_date'], a['id']))
                grouped_activities[res_id][activity_type_id.id]['attachments_info'] = {
                    'most_recent_id': most_recent_attachment['id'],
                    'most_recent_name': most_recent_attachment['name'],
                    'count': len(attachments),
                }

        # Get record ids ordered by oldest deadline (urgent one first)
        ongoing_res_ids = sorted(res_id_to_deadline, key=lambda item: res_id_to_deadline[item])
        # Get record ids with only completed activities ordered by date done reversed (most recently done first)
        completed_res_ids = [
            res_id for res_id in sorted(
                res_id_to_date_done, key=lambda item: res_id_to_date_done[item], reverse=True
            ) if res_id not in res_id_to_deadline
        ]
        return {
            'activity_res_ids': ongoing_res_ids + completed_res_ids,
            'activity_types': [
                {
                    'id': activity_type.id,
                    'name': activity_type.name,
                    'template_ids': [
                        {'id': mail_template_id.id, 'name': mail_template_id.name}
                        for mail_template_id in activity_type.mail_template_ids
                    ],
                }
                for activity_type in activity_types
            ],
            'grouped_activities': grouped_activities,
        }

    # ----------------------------------------------------------------------
    # TOOLS
    # ----------------------------------------------------------------------

    def _classify_by_model(self):
        """ To ease batch computation of various activities related methods they
        are classified by model. Activities not linked to a valid record through
        res_model / res_id are ignored.

        :returns: for each model having at least one activity in self, have
          a sub-dict containing
            * activities: activities related to that model;
            * record IDs: record linked to the activities of that model, in same
              order;
        :rtype: dict
        """
        data_by_model = {}
        for activity in self.filtered(lambda act: act.res_model and act.res_id):
            if activity.res_model not in data_by_model:
                data_by_model[activity.res_model] = {
                    'activities': self.env['mail.activity'],
                    'record_ids': [],
                }
            data_by_model[activity.res_model]['activities'] += activity
            data_by_model[activity.res_model]['record_ids'].append(activity.res_id)
        return data_by_model

    @api.autovacuum
    def _gc_delete_old_overdue_activities(self):
        """
        Delete old overdue activities
        - If the config_parameter is deleted or 0, the user doesn't want to run this gc routine
        - If the config_parameter is set to a negative number, it's an invalid value, we skip the gc routine
        - If the config_parameter is set to a positive number, we delete only overdue activities which deadline is older than X years
        """
        year_threshold = self.env['ir.config_parameter'].sudo().get_int('mail.activity.gc.delete_overdue_years')
        if year_threshold == 0:
            _logger.warning("The ir.config_parameter 'mail.activity.gc.delete_overdue_years' is missing or set to 0. Skipping gc routine.")
            return
        if year_threshold < 0:
            _logger.warning("The ir.config_parameter 'mail.activity.gc.delete_overdue_years' is set to a negative number "
                            "which is invalid. Skipping gc routine.")
            return
        deadline_threshold_dt = datetime.now() - relativedelta(years=year_threshold)
        old_overdue_activities = self.env['mail.activity'].search([('date_deadline', '<', deadline_threshold_dt)], limit=10_000)
        old_overdue_activities.unlink()
