from datetime import date
from decimal import Decimal, ROUND_HALF_UP
from django.core.exceptions import ValidationError
from django.db import transaction
from django.db.models import Sum

from .models import GoodsReceiptLine, ItemMaster, StockBatch, StockMovement, Warehouse


class InventoryValuationService:
    """FIFO, Weighted Average Cost & Specific Identification engine with atomic negative-stock guard."""

    @staticmethod
    def get_item_warehouse_balance(company, warehouse: Warehouse, item: ItemMaster) -> tuple[Decimal, Decimal]:
        agg = StockBatch.objects.filter(
            company=company, warehouse=warehouse, item=item, remaining_qty__gt=0
        ).aggregate(qty=Sum("remaining_qty"))
        qty = agg["qty"] or Decimal("0.000")
        val = Decimal("0.00")
        for b in StockBatch.objects.filter(company=company, warehouse=warehouse, item=item, remaining_qty__gt=0):
            val += (b.remaining_qty * b.unit_cost)
        return qty.quantize(Decimal("0.001")), val.quantize(Decimal("0.01"))

    @staticmethod
    def get_valuation_report(company, warehouse_id: str | None = None) -> list[dict]:
        items = ItemMaster.objects.select_related("category", "primary_unit").filter(company=company, is_active=True)
        wh_filter = {"warehouse_id": warehouse_id} if warehouse_id else {}
        rows = []
        for it in items:
            batches = StockBatch.objects.select_related("warehouse").filter(
                company=company, item=it, remaining_qty__gt=0, **wh_filter
            )
            qty = Decimal("0.000")
            val = Decimal("0.00")
            for b in batches:
                qty += b.remaining_qty
                val += b.remaining_qty * b.unit_cost
            avg_rate = (val / qty).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) if qty > 0 else it.last_purchase_rate
            rows.append(
                {
                    "item_id": str(it.id),
                    "item_code": it.item_code,
                    "name": it.name,
                    "category": it.category.name,
                    "unit": it.primary_unit.code,
                    "valuation_method": it.valuation_method,
                    "qty_on_hand": str(qty.quantize(Decimal("0.001"))),
                    "reorder_level": str(it.reorder_level),
                    "is_low_stock": qty <= it.reorder_level,
                    "weighted_avg_cost": str(avg_rate),
                    "total_value": str(val.quantize(Decimal("0.01"))),
                }
            )
        return rows

    @staticmethod
    @transaction.atomic
    def receive_stock(
        *,
        company,
        warehouse: Warehouse,
        item: ItemMaster,
        qty: Decimal,
        unit_cost: Decimal,
        movement_date: date,
        movement_type: str,
        reference_no: str,
        user,
        batch_no: str = "GENERAL",
        serial_no: str = "",
        expiry_date=None,
        grn_line: GoodsReceiptLine | None = None,
        project=None,
        site=None,
        voucher=None,
    ) -> tuple[StockBatch, StockMovement]:
        if qty <= 0:
            raise ValidationError("Receipt quantity must exceed zero.")
        batch = StockBatch.objects.create(
            company=company,
            warehouse=warehouse,
            item=item,
            batch_no=batch_no or "GENERAL",
            serial_no=serial_no,
            expiry_date=expiry_date,
            received_date=movement_date,
            received_qty=qty,
            remaining_qty=qty,
            unit_cost=unit_cost,
            grn_line=grn_line,
        )
        val_delta = (qty * unit_cost).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
        bal_qty, bal_val = InventoryValuationService.get_item_warehouse_balance(company, warehouse, item)
        mv = StockMovement.objects.create(
            company=company,
            warehouse=warehouse,
            item=item,
            batch=batch,
            movement_type=movement_type,
            movement_date=movement_date,
            reference_no=reference_no,
            quantity_delta=qty,
            unit_cost=unit_cost,
            value_delta=val_delta,
            balance_qty_after=bal_qty,
            balance_value_after=bal_val,
            project=project,
            site=site,
            voucher=voucher,
            created_by=user,
        )
        return batch, mv

    @staticmethod
    @transaction.atomic
    def consume_stock(
        *,
        company,
        warehouse: Warehouse,
        item: ItemMaster,
        qty: Decimal,
        movement_type: str,
        movement_date: date,
        reference_no: str,
        user,
        project=None,
        site=None,
        cost_code=None,
        boq_item=None,
        voucher=None,
        specific_batch: StockBatch | None = None,
    ) -> Decimal:
        """Consumes inventory atomically using item valuation_method (FIFO / WEIGHTED_AVG / SPECIFIC_ID)."""
        if qty <= 0:
            raise ValidationError("Issue quantity must exceed zero.")

        warehouse = Warehouse.objects.select_for_update().get(id=warehouse.id, company=company)
        batches = list(
            StockBatch.objects.select_for_update()
            .filter(company=company, warehouse=warehouse, item=item, remaining_qty__gt=0)
            .order_by("received_date", "id")
        )
        avail = sum((b.remaining_qty for b in batches), Decimal("0.000"))
        if qty > avail and not warehouse.allow_negative_stock:
            raise ValidationError(
                f"Insufficient stock for {item.item_code} in {warehouse.name}: available {avail}, requested {qty}."
            )

        total_cost = Decimal("0.00")

        if item.valuation_method == ItemMaster.ValuationMethod.SPECIFIC_ID and specific_batch:
            sb = StockBatch.objects.select_for_update().get(pk=specific_batch.pk)
            if qty > sb.remaining_qty:
                raise ValidationError(f"Specific batch {sb.batch_no} has only {sb.remaining_qty} remaining.")
            sb.remaining_qty -= qty
            sb.save(update_fields=["remaining_qty"])
            cost = (qty * sb.unit_cost).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
            total_cost += cost
            bal_q, bal_v = InventoryValuationService.get_item_warehouse_balance(company, warehouse, item)
            StockMovement.objects.create(
                company=company,
                warehouse=warehouse,
                item=item,
                batch=sb,
                movement_type=movement_type,
                movement_date=movement_date,
                reference_no=reference_no,
                quantity_delta=-qty,
                unit_cost=sb.unit_cost,
                value_delta=-cost,
                balance_qty_after=bal_q,
                balance_value_after=bal_v,
                project=project,
                site=site,
                cost_code=cost_code,
                boq_item=boq_item,
                voucher=voucher,
                created_by=user,
            )
            return total_cost

        if item.valuation_method == ItemMaster.ValuationMethod.WEIGHTED_AVG:
            total_val = sum((b.remaining_qty * b.unit_cost for b in batches), Decimal("0.00"))
            wac = (total_val / avail).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) if avail > 0 else item.standard_rate
            rem = qty
            for b in batches:
                if rem <= 0:
                    break
                take = min(b.remaining_qty, rem)
                b.remaining_qty -= take
                b.save(update_fields=["remaining_qty"])
                rem -= take
            total_cost = (qty * wac).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
            bal_q, bal_v = InventoryValuationService.get_item_warehouse_balance(company, warehouse, item)
            StockMovement.objects.create(
                company=company,
                warehouse=warehouse,
                item=item,
                movement_type=movement_type,
                movement_date=movement_date,
                reference_no=reference_no,
                quantity_delta=-qty,
                unit_cost=wac,
                value_delta=-total_cost,
                balance_qty_after=bal_q,
                balance_value_after=bal_v,
                project=project,
                site=site,
                cost_code=cost_code,
                boq_item=boq_item,
                voucher=voucher,
                created_by=user,
            )
            return total_cost

        # FIFO (Default exact layer queue depletion)
        rem = qty
        for b in batches:
            if rem <= 0:
                break
            take = min(b.remaining_qty, rem)
            b.remaining_qty -= take
            b.save(update_fields=["remaining_qty"])
            rem -= take
            layer_cost = (take * b.unit_cost).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
            total_cost += layer_cost
            bal_q, bal_v = InventoryValuationService.get_item_warehouse_balance(company, warehouse, item)
            StockMovement.objects.create(
                company=company,
                warehouse=warehouse,
                item=item,
                batch=b,
                movement_type=movement_type,
                movement_date=movement_date,
                reference_no=reference_no,
                quantity_delta=-take,
                unit_cost=b.unit_cost,
                value_delta=-layer_cost,
                balance_qty_after=bal_q,
                balance_value_after=bal_v,
                project=project,
                site=site,
                cost_code=cost_code,
                boq_item=boq_item,
                voucher=voucher,
                created_by=user,
            )
        return total_cost.quantize(Decimal("0.01"))

