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

from odoo import models, fields, api, _
from odoo.exceptions import UserError
from odoo.tools import date_utils
import logging

_logger = logging.getLogger(__name__)


class FamilyBankReportWizard(models.TransientModel):
    _name = 'family.bank.report.wizard'
    _description = 'Family Bank Report'

    start_date = fields.Date(
        string="Start Date",
        default=lambda self: date_utils.start_of(fields.Date.today(), 'month'),
        required=True
    )
    end_date = fields.Date(
        string="End Date",
        default=lambda self: date_utils.end_of(fields.Date.today(), 'month'),
        required=True
    )
    payment_order_ids = fields.Many2many(comodel_name='payment.orders',
                                         string="Payment Orders", required=True,
                                         domain="[('state', '=', 'waiting_deposit'),('payment_order_date','>=', start_date),('payment_order_date','<=', end_date)]")
    currency_id = fields.Many2one('res.currency', string='Currency', default=lambda self: self.env.company.currency_id)
    total_amount = fields.Monetary(string="Total Amount", compute='_compute_total_amount', store=False, currency_field='currency_id')

    @api.depends('payment_order_ids', 'payment_order_ids.total_amount')
    def _compute_total_amount(self):
        """Compute total amount from selected payment orders."""
        for record in self:
            record.total_amount = sum(record.payment_order_ids.mapped('total_amount'))

    def action_print_bank_report(self):
        try:
            _logger.info("=== WIZARD: action_print_bank_report START (Refactored) ===")
            _logger.info("Payment orders selected: %s", len(self.payment_order_ids))
            
            if not self.payment_order_ids:
                raise UserError(_("Please select at least one Payment Order."))

            moves = self.payment_order_ids.mapped('move_id')
            
            if not moves:
                raise UserError(_("Selected Payment Orders do not reference any posted moves."))

            # Optimization: 
            # We REMOVED the data grouping logic from here. 
            # Instead, we let the Report AbstractModel handle the data fetching using the Wizard record (objs).
            # This prevents passing massive JSON data through the client/URL, avoiding 502/414 errors for large datasets.
            
            # Pass only minimal metadata if needed (start/end dates are also on the wizard record, so strictly not needed but harmless)
            datas = {
                'start_date': self.start_date,
                'end_date': self.end_date,
            }
            
            _logger.info("=== WIZARD: Calling report_action (No heavy data payload) ===")
            result = self.env.ref('odex_benefit.action_family_bank_report_xlsx').report_action(self, data=datas)
            _logger.info("=== WIZARD: report_action returned successfully ===")
            return result
            
        except Exception as e:
            _logger.error("=== WIZARD: action_print_bank_report FAILED ===")
            _logger.error("Error type: %s", type(e).__name__)
            _logger.error("Error message: %s", str(e))
            import traceback
            _logger.error("Full traceback:\n%s", traceback.format_exc())
            raise
