# -*- coding: utf-8 -*-
from odoo import api, fields, models

class AccountMove(models.Model):

    _inherit = 'account.move'

    attach_no = fields.Integer(compute='get_attachments')
    res_id = fields.Integer()
    res_model = fields.Char()

    def get_attachments(self):
        print("=== get_attachments START ===")
        Attachment = self.env['ir.attachment']
        action = self.env['ir.actions.act_window']._for_xml_id('base.action_attachment')

        if len(self) > 1:
            print("Multiple records mode - len:", len(self))
            all_models_ids = set()

            for record in self:
                related_pairs = set()
                related_pairs.add((record._name, record.id))

                # PO مباشر أو تلقائي من origin/ref
                po_id = record.purchase_id.id if record.purchase_id else False
                if not po_id and record.invoice_origin:
                    po = self.env['purchase.order'].search([('name', '=', record.invoice_origin)], limit=1)
                    if po:
                        po_id = po.id
                        print("Auto-found PO by origin:", po_id)
                elif not po_id and record.ref:
                    po = self.env['purchase.order'].search([('name', '=', record.ref)], limit=1)
                    if po:
                        po_id = po.id
                        print("Auto-found PO by ref:", po_id)

                if po_id:
                    po = self.env['purchase.order'].browse(po_id)
                    related_pairs.add((po._name, po.id))
                    print("Added PO:", (po._name, po.id))

                    # Request ID - آمن
                    if hasattr(po, 'request_id') and po.request_id:
                        related_pairs.add((po.request_id._name, po.request_id.id))
                        print("Added request:", (po.request_id._name, po.request_id.id))
                    else:
                        print("NO request_id")

                    # Requisition ID - آمن
                    if hasattr(po,
                               'requisition_id') and po.requisition_id and po.requisition_id._name == 'purchase.requisition':
                        related_pairs.add(('purchase.requisition', po.requisition_id.id))
                        print("Added requisition:", ('purchase.requisition', po.requisition_id.id))
                    else:
                        print("NO requisition_id")

                    # Confirmation IDs - آمن
                    if hasattr(po, 'confirmation_ids') and po.confirmation_ids:
                        for conf in po.confirmation_ids:
                            related_pairs.add(('budget.confirmation', conf.id))
                            print("Added confirmation:", ('budget.confirmation', conf.id))
                    else:
                        print("NO confirmation_ids")

                print("Record related_pairs:", related_pairs)
                all_models_ids.update(related_pairs)

            # Build domain...
            domain = []
            pairs = list(all_models_ids)
            if pairs:
                domain = ['|'] * (len(pairs) - 1)
                for model, res_id in pairs:
                    domain.extend(['&', ('res_model', '=', model), ('res_id', '=', res_id)])

            action['domain'] = domain
            action['context'] = {'default_res_model': self[0]._name, 'default_res_id': self[0].id}

            for record in self:
                record.attach_no = Attachment.search_count(
                    [('res_model', '=', record._name), ('res_id', '=', record.id)])
            print("=== MULTIPLE END ===")
            return action

        # Single record - تلقائي
        self.ensure_one()
        print("SINGLE RECORD ID:", self.id)
        print("invoice_origin:", self.invoice_origin, "ref:", self.ref)

        related_pairs = [(self._name, self.id)]

        # PO تلقائي
        po_id = self.purchase_id.id if self.purchase_id else False
        if not po_id and self.invoice_origin:
            po = self.env['purchase.order'].search([('name', '=', self.invoice_origin)], limit=1)
            if po: po_id = po.id
        elif not po_id and self.ref:
            po = self.env['purchase.order'].search([('name', '=', self.ref)], limit=1)
            if po: po_id = po.id

        if po_id:
            po = self.env['purchase.order'].browse(po_id)
            related_pairs.append((po._name, po.id))
            print("Auto-linked PO:", po_id)

            if hasattr(po, 'request_id') and po.request_id:
                related_pairs.append((po.request_id._name, po.request_id.id))
            if hasattr(po,
                       'requisition_id') and po.requisition_id and po.requisition_id._name == 'purchase.requisition':
                related_pairs.append(('purchase.requisition', po.requisition_id.id))
            if hasattr(po, 'confirmation_ids') and po.confirmation_ids:
                for conf in po.confirmation_ids:
                    related_pairs.append(('budget.confirmation', conf.id))

        # Domain
        domain = []
        if len(related_pairs) > 1:
            domain = ['|'] * (len(related_pairs) - 1)
            for model, res_id in related_pairs:
                domain.extend(['&', ('res_model', '=', model), ('res_id', '=', res_id)])
        else:
            domain = [('res_model', '=', self._name), ('res_id', '=', self.id)]

        action['domain'] = domain
        action['context'] = {'default_res_model': self._name, 'default_res_id': self.id}
        self.attach_no = Attachment.search_count(domain)
        print("attach_no:", self.attach_no, "Domain covers:", related_pairs)
        print("=== END ===")
        return action



