from odoo import api, models


class ReportTemplateUsage(models.AbstractModel):
    _name = 'report.do_mail_quick_templates.report_template_usage'
    _description = 'Quick Template Usage Report'

    def _top_user_name(self, template):
        Log = self.env['mail.quick.template.log']
        groups = Log._read_group(
            [('template_id', '=', template.id), ('user_id', '!=', False)],
            groupby=['user_id'], aggregates=['__count'],
            order='__count desc', limit=1,
        )
        return groups[0][0].name if groups else 'N/A'

    @api.model
    def _get_report_values(self, docids, data=None):
        templates = self.env['mail.quick.template'].browse(docids)

        # Group templates by category, preserving category sequence order.
        categories = {}
        for tmpl in templates:
            cat = tmpl.category_id
            key = cat.id or 0
            if key not in categories:
                categories[key] = {
                    'name': cat.name or 'Other',
                    'sequence': cat.sequence if cat else 9999,
                    'lines': [],
                    'subtotal': 0,
                }
            categories[key]['lines'].append({
                'name': tmpl.name,
                'category': cat.name or 'Other',
                'model': tmpl.model_id.name or 'Global',
                'use_count': tmpl.use_count,
                'last_used': tmpl.last_used_date,
                'top_user': self._top_user_name(tmpl),
            })
            categories[key]['subtotal'] += tmpl.use_count

        ordered = sorted(categories.values(), key=lambda c: (c['sequence'], c['name']))
        grand_total = sum(c['subtotal'] for c in ordered)

        return {
            'doc_ids': docids,
            'doc_model': 'mail.quick.template',
            'docs': templates,
            'categories': ordered,
            'grand_total': grand_total,
            'company': self.env.company,
        }
