import logging

from odoo import models

_logger = logging.getLogger(__name__)


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

    def action_update_lines_from_list_price(self):
        """Copy current product list price into sale order lines.

        Applies to orders that are not fully invoiced. Skips display and
        downpayment lines, keeps discounts. Totals/taxes are recomputed by
        field dependencies when the lines change.
        """

        eligible_orders = self.filtered(
            lambda so: so.invoice_status not in ("invoiced", "up_to_date")
            and so.state != "cancel"
        )

        if not eligible_orders:
            return {
                "type": "ir.actions.client",
                "tag": "display_notification",
                "params": {
                    "title": self.env._("Update skipped"),
                    "message": self.env._(
                        "No sales orders to update. Only non-invoiced and non-canceled orders are processed."
                    ),
                    "type": "warning",
                    "sticky": False,
                },
            }

        total_lines = 0
        for order in eligible_orders:
            lines = order.order_line.filtered(
                lambda line: not line.display_type
                and not line.is_downpayment
                and line.product_id
            )
            for line in lines:
                price_unit = line.product_id.uom_id._compute_price(
                    line.product_id.lst_price, line.product_uom
                )
                line.price_unit = price_unit

            total_lines += len(lines)
            _logger.info(
                "[SALE PRICE UPDATE] Order %s (%s): updated %s lines",
                order.name,
                order.id,
                len(lines),
            )

        return {
            "type": "ir.actions.client",
            "tag": "display_notification",
            "params": {
                "title": self.env._("Sales price update"),
                "message": self.env._(
                    "Updated %(lines)s lines across %(orders)s sales orders.",
                    lines=total_lines,
                    orders=len(eligible_orders),
                ),
                "type": "success" if total_lines else "warning",
                "sticky": False,
            },
        }
