# -*- coding: utf-8 -*-
# Copyright 2026 Nexa Systems Inc.
# License OPL-1 (Odoo Proprietary License v1.0)

import base64
import logging

from odoo import api, fields, models, _
from odoo.exceptions import UserError

_logger = logging.getLogger(__name__)


class SendFaxWizard(models.TransientModel):
    _name = 'fusion_faxes.send.fax.wizard'
    _description = 'Send Fax Wizard'

    partner_id = fields.Many2one(
        'res.partner',
        string='Recipient',
        required=True,
    )
    fax_number = fields.Char(
        string='Fax Number',
        required=True,
    )
    cover_page_text = fields.Text(
        string='Cover Page Text',
    )
    document_line_ids = fields.One2many(
        'fusion_faxes.send.fax.wizard.line',
        'wizard_id',
        string='Documents',
    )
    generate_pdf = fields.Boolean(
        string='Attach PDF of Source Document',
        default=True,
        help='Automatically generate and attach a PDF of the sale order or invoice.',
    )

    # Context links
    sale_order_id = fields.Many2one('sale.order', string='Sale Order')
    account_move_id = fields.Many2one('account.move', string='Invoice')

    @api.onchange('partner_id')
    def _onchange_partner_id(self):
        if self.partner_id and self.partner_id.x_ff_fax_number:
            self.fax_number = self.partner_id.x_ff_fax_number

    @api.model
    def default_get(self, fields_list):
        res = super().default_get(fields_list)
        context = self.env.context

        # Auto-fill from sale order context
        if context.get('active_model') == 'sale.order' and context.get('active_id'):
            order = self.env['sale.order'].browse(context['active_id'])
            res['sale_order_id'] = order.id
            res['partner_id'] = order.partner_id.id
            if order.partner_id.x_ff_fax_number:
                res['fax_number'] = order.partner_id.x_ff_fax_number

        # Auto-fill from invoice context
        elif context.get('active_model') == 'account.move' and context.get('active_id'):
            move = self.env['account.move'].browse(context['active_id'])
            res['account_move_id'] = move.id
            res['partner_id'] = move.partner_id.id
            if move.partner_id.x_ff_fax_number:
                res['fax_number'] = move.partner_id.x_ff_fax_number

        # Pre-attach documents when forwarding a fax
        forward_ids = context.get('forward_attachment_ids')
        if forward_ids:
            lines = []
            for seq, att_id in enumerate(forward_ids, start=1):
                lines.append((0, 0, {
                    'sequence': seq * 10,
                    'attachment_id': att_id,
                    'file_name': self.env['ir.attachment'].browse(att_id).name,
                }))
            res['document_line_ids'] = lines
            res['generate_pdf'] = False

        return res

    def _generate_source_pdf(self):
        """Generate a PDF of the linked sale order or invoice."""
        self.ensure_one()
        if self.sale_order_id:
            report = self.env.ref('sale.action_report_saleorder')
            pdf_content, _ = report._render_qweb_pdf(report.id, [self.sale_order_id.id])
            filename = f'{self.sale_order_id.name}.pdf'
            return filename, pdf_content
        elif self.account_move_id:
            report = self.env.ref('account.account_invoices')
            pdf_content, _ = report._render_qweb_pdf(report.id, [self.account_move_id.id])
            filename = f'{self.account_move_id.name}.pdf'
            return filename, pdf_content
        return None, None

    def action_send(self):
        """Create a fusion.fax record and send it."""
        self.ensure_one()

        if not self.fax_number:
            raise UserError(_('Please enter a fax number.'))

        # Collect attachment IDs from ordered wizard lines
        ordered_attachment_ids = list(
            self.document_line_ids.sorted('sequence').mapped('attachment_id').ids
        )

        # Generate PDF of source document if requested
        if self.generate_pdf:
            filename, pdf_content = self._generate_source_pdf()
            if pdf_content:
                attachment = self.env['ir.attachment'].create({
                    'name': filename,
                    'type': 'binary',
                    'datas': base64.b64encode(pdf_content),
                    'mimetype': 'application/pdf',
                    'res_model': 'fusion.fax',
                })
                # Generated PDF goes first (sequence 1)
                ordered_attachment_ids.insert(0, attachment.id)

        if not ordered_attachment_ids:
            raise UserError(_('Please attach at least one document or enable PDF generation.'))

        # Build document lines preserving the wizard ordering
        document_lines = []
        for seq, att_id in enumerate(ordered_attachment_ids, start=1):
            document_lines.append((0, 0, {
                'sequence': seq * 10,
                'attachment_id': att_id,
            }))

        # Create the fax record
        fax = self.env['fusion.fax'].create({
            'partner_id': self.partner_id.id,
            'fax_number': self.fax_number,
            'cover_page_text': self.cover_page_text,
            'document_ids': document_lines,
            'sale_order_id': self.sale_order_id.id if self.sale_order_id else False,
            'account_move_id': self.account_move_id.id if self.account_move_id else False,
            'sent_by_id': self.env.user.id,
        })

        # Send immediately
        fax._send_fax()

        return {
            'type': 'ir.actions.client',
            'tag': 'display_notification',
            'params': {
                'title': _('Fax Sent'),
                'message': _('Fax %s sent successfully to %s.') % (fax.name, self.fax_number),
                'type': 'success',
                'sticky': False,
                'next': {'type': 'ir.actions.act_window_close'},
            },
        }
