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

import logging
from odoo import models, fields, api

_logger = logging.getLogger(__name__)


class ProductTemplateAttributeValue(models.Model):
    _inherit = 'product.template.attribute.value'

    x_fi_extra_cost = fields.Float(
        string='Extra Cost',
        default=0.0,
        digits='Product Price',
        help='Additional cost incurred for this attribute value. '
             'Included in the total cost base before margin is applied. '
             'Unlike Extra Price, margin IS calculated on this amount.')

    x_fi_extra_price_impact = fields.Float(
        string='+ Price (from Cost)',
        compute='_compute_extra_price_impact',
        digits='Product Price',
        help='The sale price increase resulting from this Extra Cost '
             'after applying the product margin. '
             'e.g. $40 extra cost at 50%% margin = +$80 in sale price.')

    @api.depends('x_fi_extra_cost', 'product_tmpl_id.x_fi_margin_pct')
    def _compute_extra_price_impact(self):
        for ptav in self:
            cost = ptav.x_fi_extra_cost or 0.0
            margin = ptav.product_tmpl_id.x_fi_margin_pct or 0.0
            if cost > 0 and 0 < margin < 100:
                ptav.x_fi_extra_price_impact = round(
                    cost / (1 - margin / 100), 2)
            else:
                ptav.x_fi_extra_price_impact = cost

    def write(self, vals):
        res = super().write(vals)
        if 'x_fi_extra_cost' in vals:
            self._recalculate_variant_prices()
        return res

    def _recalculate_variant_prices(self):
        """When extra cost changes, adjust variant prices to maintain margin."""
        ProductProduct = self.env['product.product']
        variants = ProductProduct.search([
            ('product_template_attribute_value_ids', 'in', self.ids)
        ])
        if not variants:
            return
        variants._compute_cost_extra()
        for var in variants:
            margin = var.x_fi_variant_margin_pct or 0.0
            eff = (var.standard_price
                   + (var.x_fi_shipping_cost or 0.0)
                   + (var.x_fi_cost_extra or 0.0))
            if eff > 0 and 0 < margin < 100:
                base = round(eff / (1 - margin / 100), 2)
                new_offset = round(base - var.list_price, 2)
                if abs((var.x_fi_price_offset or 0.0) - new_offset) > 0.001:
                    var.x_fi_price_offset = new_offset
                    _logger.info(
                        'Extra cost changed -> updated offset for %s: %.2f',
                        var.display_name, new_offset)
