# Copyright 2025 Criptomart
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).

from odoo import api, fields, models


class StockValuationLayer(models.Model):
    _inherit = "stock.valuation.layer"

    # Make categ_id stored to allow grouping in reports
    categ_id = fields.Many2one(store=True, index=True)

    # Category hierarchy levels for grouping
    categ_level_1_id = fields.Many2one(
        comodel_name="product.category",
        string="Category Level 1",
        compute="_compute_category_levels",
        store=True,
        index=True,
    )
    categ_level_2_id = fields.Many2one(
        comodel_name="product.category",
        string="Category Level 2",
        compute="_compute_category_levels",
        store=True,
        index=True,
    )
    categ_level_3_id = fields.Many2one(
        comodel_name="product.category",
        string="Category Level 3",
        compute="_compute_category_levels",
        store=True,
        index=True,
    )
    categ_level_4_id = fields.Many2one(
        comodel_name="product.category",
        string="Category Level 4",
        compute="_compute_category_levels",
        store=True,
        index=True,
    )

    @api.depends("categ_id", "categ_id.parent_path")
    def _compute_category_levels(self):
        """Compute category hierarchy levels for better grouping options."""
        for layer in self:
            if not layer.categ_id or not layer.categ_id.parent_path:
                layer.categ_level_1_id = False
                layer.categ_level_2_id = False
                layer.categ_level_3_id = False
                layer.categ_level_4_id = False
                continue

            # parent_path format: "1/2/3/" where each number is a category ID
            path_ids = [
                int(x) for x in layer.categ_id.parent_path.split("/") if x.isdigit()
            ]

            # Assign levels based on hierarchy
            layer.categ_level_1_id = path_ids[0] if len(path_ids) >= 1 else False
            layer.categ_level_2_id = path_ids[1] if len(path_ids) >= 2 else False
            layer.categ_level_3_id = path_ids[2] if len(path_ids) >= 3 else False
            layer.categ_level_4_id = path_ids[3] if len(path_ids) >= 4 else False
