from __future__ import annotations

from django.core.exceptions import ValidationError
from django.db import transaction
from django.db.models import F
from django.utils import timezone

from apps.core.services import audit, format_number, next_sequence
from apps.sync.services import emit

from .models import (InventoryCount, InventoryCountLine, Item, StockMovement,
                     StockTransfer, StockTransferLine)


@transaction.atomic
def record_movement(*, actor, item: Item, movement_type: str, quantity: int,
                    reason: str = "", reference: str = "", unit_cost: int | None = None) -> StockMovement:
    item = Item.objects.select_for_update().get(pk=item.pk)
    if movement_type not in {"ENTRY", "ISSUE", "ADJUSTMENT"}:
        raise ValidationError("Type de mouvement invalide.")
    signed = quantity if movement_type == "ENTRY" else -quantity
    if movement_type == "ADJUSTMENT":
        signed = quantity  # quantité signée saisie
    if signed < 0 and item.current_qty + signed < 0:
        raise ValidationError(f"Stock insuffisant : {item.current_qty} {item.unit} disponible(s).")
    cost = unit_cost if unit_cost is not None else item.average_cost_xaf or item.unit_cost_xaf
    movement = StockMovement.objects.create(
        agency=item.agency, item=item, movement_type=movement_type, quantity=signed,
        unit_cost_xaf=cost, total_cost_xaf=abs(signed) * cost,
        reason=reason, reference=reference, actor=actor,
    )
    item.current_qty = item.current_qty + signed
    if movement_type == "ENTRY" and signed > 0:
        total_value = item.average_cost_xaf * (item.current_qty - signed) + cost * signed
        item.average_cost_xaf = round(total_value / item.current_qty) if item.current_qty else cost
        item.unit_cost_xaf = cost
    item.version += 1
    item.save(update_fields=["current_qty", "average_cost_xaf", "unit_cost_xaf", "version", "updated_at"])
    audit(action="STOCK_MOVEMENT", actor=actor, entity=item, agency_id=item.agency_id,
          after={"type": movement_type, "quantity": signed, "balance": item.current_qty})
    emit(entity=movement, op_type="APPEND", actor=actor, agency_id=item.agency_id)
    return movement


@transaction.atomic
def create_transfer(*, actor, from_agency, to_agency, lines: list[dict], note: str = "") -> StockTransfer:
    if from_agency.id == to_agency.id:
        raise ValidationError("Les agences émettrice et réceptrice doivent être différentes.")
    seq = next_sequence(from_agency.id, "transfer", year=timezone.localdate().year)
    transfer = StockTransfer.objects.create(
        code=format_number(from_agency.code, "TRF", seq, width=4),
        from_agency=from_agency, to_agency=to_agency, note=note, created_by=actor,
    )
    for line in lines:
        if line["quantity"] <= 0:
            continue
        StockTransferLine.objects.create(transfer=transfer, item=line["item"],
                                         quantity=line["quantity"],
                                         unit_cost_xaf=line["item"].average_cost_xaf)
    audit(action="STOCK_TRANSFER_CREATED", actor=actor, entity=transfer, agency_id=from_agency.id)
    return transfer


@transaction.atomic
def ship_transfer(*, actor, transfer: StockTransfer) -> StockTransfer:
    transfer = StockTransfer.objects.select_for_update().get(pk=transfer.pk)
    if transfer.status not in {"DRAFT", "PENDING", "APPROVED"}:
        raise ValidationError("Ce transfert ne peut pas être expédié.")
    for line in transfer.lines.select_related("item"):
        item = Item.objects.select_for_update().get(pk=line.item_id)
        if item.current_qty < line.quantity:
            raise ValidationError(f"Stock insuffisant pour {item.name}.")
        StockMovement.objects.create(
            agency=transfer.from_agency, item=item, movement_type="TRANSFER_OUT",
            quantity=-line.quantity, unit_cost_xaf=line.unit_cost_xaf,
            total_cost_xaf=line.quantity * line.unit_cost_xaf,
            reason=f"Transfert {transfer.code}", transfer=transfer, actor=actor,
        )
        item.current_qty -= line.quantity
        item.version += 1
        item.save(update_fields=["current_qty", "version", "updated_at"])
    transfer.status = "SHIPPED"
    transfer.shipped_by = actor
    transfer.shipped_at = timezone.now()
    transfer.save(update_fields=["status", "shipped_by", "shipped_at"])
    audit(action="STOCK_TRANSFER_SHIPPED", actor=actor, entity=transfer, agency_id=transfer.from_agency_id)
    emit(entity=transfer, op_type="STATE", actor=actor, agency_id=transfer.from_agency_id)
    return transfer


@transaction.atomic
def receive_transfer(*, actor, transfer: StockTransfer) -> StockTransfer:
    transfer = StockTransfer.objects.select_for_update().get(pk=transfer.pk)
    if transfer.status != "SHIPPED":
        raise ValidationError("Seul un transfert expédié peut être réceptionné.")
    for line in transfer.lines.select_related("item"):
        target, _ = Item.objects.select_for_update().get_or_create(
            agency=transfer.to_agency, code=line.item.code,
            defaults={"category": line.item.category, "name": line.item.name, "unit": line.item.unit,
                      "unit_cost_xaf": line.unit_cost_xaf, "average_cost_xaf": line.unit_cost_xaf,
                      "location": ""},
        )
        StockMovement.objects.create(
            agency=transfer.to_agency, item=target, movement_type="TRANSFER_IN",
            quantity=line.quantity, unit_cost_xaf=line.unit_cost_xaf,
            total_cost_xaf=line.quantity * line.unit_cost_xaf,
            reason=f"Réception transfert {transfer.code}", transfer=transfer, actor=actor,
        )
        target.current_qty += line.quantity
        target.version += 1
        target.save(update_fields=["current_qty", "version", "updated_at"])
    transfer.status = "RECEIVED"
    transfer.received_by = actor
    transfer.received_at = timezone.now()
    transfer.save(update_fields=["status", "received_by", "received_at"])
    audit(action="STOCK_TRANSFER_RECEIVED", actor=actor, entity=transfer, agency_id=transfer.to_agency_id)
    emit(entity=transfer, op_type="STATE", actor=actor, agency_id=transfer.to_agency_id)
    return transfer


@transaction.atomic
def create_count(*, actor, agency, item_ids: list) -> InventoryCount:
    seq = next_sequence(agency.id, "inventory", year=timezone.localdate().year)
    count = InventoryCount.objects.create(
        code=format_number(agency.code, "INV", seq, width=4),
        agency=agency, responsible=actor,
    )
    for item in Item.objects.filter(agency=agency, id__in=item_ids):
        InventoryCountLine.objects.create(count=count, item=item, expected_qty=item.current_qty,
                                          counted_qty=item.current_qty, unit_cost_xaf=item.average_cost_xaf)
    return count


@transaction.atomic
def validate_count(*, actor, count: InventoryCount):
    count = InventoryCount.objects.select_for_update().get(pk=count.pk)
    if count.status == "VALIDATED":
        raise ValidationError("Cet inventaire est déjà validé.")
    for line in count.lines.select_related("item"):
        difference = line.counted_qty - line.expected_qty
        if difference == 0:
            continue
        item = Item.objects.select_for_update().get(pk=line.item_id)
        StockMovement.objects.create(
            agency=count.agency, item=item, movement_type="ADJUSTMENT", quantity=difference,
            unit_cost_xaf=line.unit_cost_xaf, total_cost_xaf=abs(difference) * line.unit_cost_xaf,
            reason=f"Inventaire {count.code}", count=count, actor=actor,
        )
        # L'écart s'applique au stock courant pour conserver les mouvements
        # enregistrés entre la création et la validation du comptage.
        item.current_qty = max(0, item.current_qty + difference)
        item.version += 1
        item.save(update_fields=["current_qty", "version", "updated_at"])
    count.status = "VALIDATED"
    count.validated_by = actor
    count.validated_at = timezone.now()
    count.save(update_fields=["status", "validated_by", "validated_at"])
    audit(action="INVENTORY_VALIDATED", actor=actor, entity=count, agency_id=count.agency_id)
