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

from odoo import fields, models
from datetime import datetime
from dateutil.relativedelta import relativedelta

import logging

_logger = logging.getLogger(__name__)


class StockMove(models.Model):
    _inherit = "stock.move"

    def get_stock_moves_by_product(self, date_begin, date_end, location):
        """
        Get stock movements grouped by product for a given date range and location.

        Args:
            date_begin (str): Start date in format 'YYYY-MM-DD'
            date_end (str): End date in format 'YYYY-MM-DD'
            location (int): Location ID to filter movements

        Returns:
            list: List of dictionaries with product and movement data
        """
        if date_begin and date_end:
            moves = self.env["stock.move"].search(
                [
                    "|",
                    ("location_id", "=", int(location)),
                    ("location_dest_id", "=", int(location)),
                    ("state", "=", "done"),
                    ("date", ">=", date_begin),
                    ("date", "<=", date_end),
                ]
            )
        else:
            return []

        moves_grouped = {}
        data = []

        if moves:
            for move in moves:
                if move.product_id.id and move.product_id.type == "product":
                    if not moves_grouped.get(move.product_id.id, False):
                        date_end_obj = datetime.strptime(
                            date_end, "%Y-%m-%d"
                        ).date() + relativedelta(days=1)
                        moves_grouped[move.product_id.id] = dict([])
                        moves_grouped[move.product_id.id]["name"] = move.product_id.name
                        moves_grouped[move.product_id.id][
                            "category"
                        ] = move.product_id.categ_id.name
                        moves_grouped[move.product_id.id][
                            "list_price"
                        ] = move.product_id.list_price
                        # Get quantity at start of period
                        moves_grouped[move.product_id.id]["qty_init"] = (
                            move.product_id.with_context(
                                {
                                    "to_date": date_begin,
                                    "location_ids": [int(location)],
                                }
                            ).qty_available
                        )
                        # Get quantity at end of period
                        moves_grouped[move.product_id.id]["qty_end"] = (
                            move.product_id.with_context(
                                {
                                    "to_date": date_end_obj,
                                    "location_ids": [int(location)],
                                }
                            ).qty_available
                        )

                    if not moves_grouped[move.product_id.id].get("in"):
                        moves_grouped[move.product_id.id]["in"] = 0.0
                    if not moves_grouped[move.product_id.id].get("out"):
                        moves_grouped[move.product_id.id]["out"] = 0.0

                    if int(move.location_id.id) == int(location):
                        moves_grouped[move.product_id.id]["out"] += move.product_qty
                    elif int(move.location_dest_id.id) == int(location):
                        moves_grouped[move.product_id.id]["in"] += move.product_qty

            data = list(moves_grouped.values())

        return data
