# -*- coding: utf-8 -*-

import json
import logging

from odoo import http
from odoo.http import request
from odoo.tools.safe_eval import safe_eval, time

_logger = logging.getLogger(__name__)


class FusionPDFPreviewController(http.Controller):

    @http.route('/fusion_pdf_preview/get_report_name', type='json', auth='user')
    def get_report_name(self, report_name=False, data=None):
        file_name = ''

        if not report_name:
            raise request.not_found(
                description="Cannot find report name in parameters")

        report = request.env['ir.actions.report']._get_report_from_name(
            report_name)
        if not report:
            raise request.not_found(
                description=f"Cannot find report with name ({report_name})")

        print_report_name = report.print_report_name
        if data:
            data = json.loads(data)
        else:
            data = {}
        res_ids = data.get('active_ids', [])
        records = request.env[report.model].browse(res_ids)
        try:
            if print_report_name and not len(records) > 1:
                file_name = safe_eval(print_report_name, {
                    'object': records, 'time': time})
        except Exception:
            _logger.warning(
                "Failed to evaluate print_report_name for report %s",
                report_name, exc_info=True)

        return {
            'file_name': file_name,
            'wkhtmltopdf_state': request.env['ir.actions.report'].get_wkhtmltopdf_state(),
            'fusion_preview_mode': report.fusion_preview_mode or 'default',
        }

    @http.route('/fusion_pdf_preview/log_action', type='json', auth='user')
    def log_action(self, report_name=False, action_type=False, record_ids=False, model_name=False):
        """Create an audit log entry for PDF preview/print/download actions."""
        if not report_name or not action_type:
            return {'success': False}

        report = request.env['ir.actions.report']._get_report_from_name(report_name)

        vals = {
            'user_id': request.env.uid,
            'report_name': report.name if report else report_name,
            'report_id': report.id if report else False,
            'action_type': action_type,
            'record_ids': record_ids or '',
            'model_name': model_name or (report.model if report else ''),
        }

        try:
            request.env['fusion.pdf.preview.log'].sudo().create(vals)
        except Exception:
            _logger.warning("Failed to create PDF preview log entry", exc_info=True)
            return {'success': False}

        return {'success': True}
