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

_logger = logging.getLogger(__name__)

class SaleOrder(models.Model):
    _inherit = 'sale.order'

    def _add_uber_delivery_fee(self, amount):
        """Add the delivery fee as a line item if not already added or update it"""
        _logger.info("Uber: Adding delivery fee %s to order %s", amount, self.name)
        config = self.env['uber.config'].sudo().search([('active', '=', True)], limit=1)
        if config and config.delivery_product_id:
            fee_product = config.delivery_product_id
            
            # Ensure product is published and sellable
            if not fee_product.website_published or not fee_product.sale_ok:
                _logger.info("Uber: Publishing and enabling sale for product %s", fee_product.name)
                fee_product.sudo().write({
                    'website_published': True,
                    'sale_ok': True
                })

            # Set fulfillment type on order if field exists
            if hasattr(self, 'fulfilment_type'):
                self.write({'fulfilment_type': 'delivery'})

            fee_line = self.order_line.filtered(lambda l: l.product_id.id == fee_product.id)
            if fee_line:
                _logger.info("Uber: Updating existing fee line %s", fee_line.id)
                fee_line.write({
                    'price_unit': amount,
                    'name': 'Uber Delivery Fee'
                })
            else:
                _logger.info("Uber: Creating new fee line for product %s", fee_product.id)
                self.write({'order_line': [(0, 0, {
                    'product_id': fee_product.id,
                    'name': 'Uber Delivery Fee',
                    'price_unit': amount,
                    'product_uom_qty': 1,
                })]})
            
            # Satisfy Odoo's shipping requirement by setting a carrier if none is set
            if not self.carrier_id:
                Carrier = self.env['delivery.carrier'].sudo()
                # Try to find an 'Uber' carrier first, then fall back to any active one
                carrier = Carrier.search([('name', 'ilike', 'uber')], limit=1) or Carrier.search([], limit=1)
                if carrier:
                    _logger.info("Uber: Linking order to carrier %s", carrier.name)
                    self.write({'carrier_id': carrier.id})
            
            # Recalculate taxes and totals
            self._amount_all()
        else:
            _logger.warning("Uber: Config or delivery product not found")
        
        return True
