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

from odoo import models, fields, api


class ProductBrand(models.Model):
    _name = 'product.brand'
    _description = 'Product Brand / Manufacturer'
    _order = 'name'
    _rec_name = 'name'
    _parent_name = 'parent_id'

    name = fields.Char(string='Brand Name', required=True, index=True)
    active = fields.Boolean(default=True)
    logo = fields.Image(string='Logo', max_width=1024, max_height=1024)

    parent_id = fields.Many2one(
        'product.brand', string='Parent Brand', index=True,
        ondelete='cascade',
        help='If set, this brand is a sub-brand of the parent.')
    child_ids = fields.One2many(
        'product.brand', 'parent_id', string='Sub-Brands')
    child_count = fields.Integer(
        string='Sub-Brands', compute='_compute_child_count')

    partner_id = fields.Many2one(
        'res.partner', string='Manufacturer / Vendor',
        domain="[('supplier_rank', '>', 0)]",
        help='The vendor or manufacturer company this brand belongs to.')

    # Brand-level default pricing (backward-compatible fallback)
    primary_discount_pct = fields.Float(
        string='Primary Discount (%)',
        help='First-tier discount off MSRP. E.g. 40 means 40%% off.')
    secondary_discount_pct = fields.Float(
        string='Secondary Discount (%)',
        help='Second-tier discount applied after the primary. '
             'E.g. 30 means 30%% off the primary-discounted price.')
    net_discount_pct = fields.Float(
        string='Effective Discount (%)',
        compute='_compute_net_discount', store=True,
        help='Combined effect of both discount tiers.')

    pricing_rule_ids = fields.One2many(
        'product.brand.pricing.rule', 'brand_id',
        string='Pricing Rules')

    notes = fields.Text(string='Pricing Notes')

    product_ids = fields.Many2many(
        'product.template', 'product_template_brand_rel',
        'brand_id', 'product_tmpl_id',
        string='Products')
    product_count = fields.Integer(
        string='Products', compute='_compute_product_count')

    @api.depends('primary_discount_pct', 'secondary_discount_pct')
    def _compute_net_discount(self):
        for brand in self:
            p = brand.primary_discount_pct or 0.0
            s = brand.secondary_discount_pct or 0.0
            remaining = (1 - p / 100) * (1 - s / 100)
            brand.net_discount_pct = round((1 - remaining) * 100, 2)

    def _compute_product_count(self):
        for brand in self:
            brand.product_count = len(brand.product_ids)

    def _compute_child_count(self):
        for brand in self:
            brand.child_count = len(brand.child_ids)

    @api.constrains('parent_id')
    def _check_parent_recursion(self):
        if not self._check_recursion():
            raise models.ValidationError('A brand cannot be its own parent.')

    def get_pricing_for_product(self, product_tmpl):
        """Walk the pricing cascade and return a matching rule, or None for brand default.

        Resolution order (first match wins):
          1. Rule scoped to this specific product
          2. Rule scoped to the product's category
          3. Rule scoped to "all products"
          4. None -> caller uses brand's own primary/secondary defaults
          5. If sub-brand with no pricing at all, delegate to parent
        """
        self.ensure_one()
        rules = self.pricing_rule_ids.filtered('active').sorted('sequence')

        for rule in rules:
            if rule.apply_on == 'product' and rule.product_tmpl_id == product_tmpl:
                return rule

        categ = product_tmpl.categ_id if product_tmpl else False
        for rule in rules:
            if rule.apply_on == 'category' and rule.categ_id == categ:
                return rule

        for rule in rules:
            if rule.apply_on == 'all':
                return rule

        has_own_pricing = (self.primary_discount_pct or self.secondary_discount_pct)
        if has_own_pricing:
            return None

        if self.parent_id:
            return self.parent_id.get_pricing_for_product(product_tmpl)

        return None

    def calculate_cost_from_msrp(self, msrp, product_tmpl=None):
        """Return expected purchase cost for a given MSRP.

        If product_tmpl is provided, uses the pricing cascade to find the
        best-matching rule. Otherwise falls back to brand-level defaults.
        """
        self.ensure_one()
        if product_tmpl:
            rule = self.get_pricing_for_product(product_tmpl)
            if rule:
                return rule.calculate_cost(msrp)

        p = self.primary_discount_pct or 0.0
        s = self.secondary_discount_pct or 0.0
        return round(msrp * (1 - p / 100) * (1 - s / 100), 2)

    def action_view_products(self):
        self.ensure_one()
        return {
            'type': 'ir.actions.act_window',
            'name': self.name,
            'res_model': 'product.template',
            'view_mode': 'list,form',
            'domain': [('x_fi_brand_ids', 'in', self.id)],
            'context': {'default_x_fi_brand_ids': [(4, self.id)]},
        }

    def action_view_sub_brands(self):
        self.ensure_one()
        return {
            'type': 'ir.actions.act_window',
            'name': f'{self.name} - Sub-Brands',
            'res_model': 'product.brand',
            'view_mode': 'list,form',
            'domain': [('parent_id', '=', self.id)],
            'context': {'default_parent_id': self.id},
        }
