from odoo import models, fields, api, _
import logging

_logger = logging.getLogger(__name__)

class PosOrder(models.Model):
    _inherit = 'pos.order'

    def action_pos_order_paid(self):
        """
        Override to deduct recipe ingredients when an order is paid.
        """
        res = super(PosOrder, self).action_pos_order_paid()
        for order in self:
            order._deduct_recipe_ingredients()
        return res

    def _deduct_recipe_ingredients(self):
        """
        Calculates and deducts total ingredients for all lines in the order.
        """
        self.ensure_one()
        
        # 1. Find a suitable Kitchen/Scrap Location
        # We assume the default warehouse's stock location for now, 
        # but in a real setup, we might want a 'Production' or 'Virtual/Consumed' location.
        location_src_id = self.config_id.warehouse_id.lot_stock_id.id
        location_dest_id = self.env.ref('stock.stock_location_customers').id # Deducting to customers
        
        # If the warehouse isn't configured, fallback to finding any internal location
        if not location_src_id:
            location_src_id = self.env['stock.location'].search([('usage', '=', 'internal')], limit=1).id

        moves = []
        for line in self.lines:
            recipe = self.env['dine360.recipe'].search([('product_tmpl_id', '=', line.product_id.product_tmpl_id.id)], limit=1)
            
            if recipe:
                for ingredient in recipe.ingredient_ids:
                    # Calculate total quantity (qty of dish * qty of ingredient in recipe)
                    total_qty = line.qty * ingredient.quantity
                    
                    moves.append({
                        'name': f"Recipe Deduction: {line.product_id.name} ({self.name})",
                        'product_id': ingredient.product_id.id,
                        'product_uom': ingredient.uom_id.id,
                        'product_uom_qty': total_qty,
                        'location_id': location_src_id,
                        'location_dest_id': location_dest_id,
                        'origin': self.name,
                        'state': 'draft',
                    })

        if moves:
            _logger.info(f"Dine360 Recipe: Creating {len(moves)} stock moves for order {self.name}")
            stock_moves = self.env['stock.move'].create(moves)
            stock_moves._action_confirm()
            stock_moves._action_assign()
            stock_moves._set_quantity_done(stock_moves.mapped('product_uom_qty')) # Simplified for Odoo 17
            # In Odoo 17, _set_quantity_done is different, using move_line_ids or quantity field.
            # Using loop for safety across sub-versions
            for move in stock_moves:
                move.quantity = move.product_uom_qty # Odoo 17 uses 'quantity' field
            stock_moves._action_done()
            
            _logger.info(f"Dine360 Recipe: Successfully deducted ingredients for {self.name}")
