from decimal import Decimal, ROUND_HALF_UP

from django.core.management.base import BaseCommand

from shop_management.models.data.shop import Shop
from shop_management.models.data.stock import Stock
from shop_management.views.data.stock import normalize_currency_code


TWOPLACES = Decimal("0.01")


class Command(BaseCommand):
    help = "Show Total Stock Value by currency for a branch (read-only)."

    def add_arguments(self, parser):
        parser.add_argument(
            "--shop-name",
            type=str,
            default="Takhar Branch",
            help="Branch name (default: Takhar Branch).",
        )
        parser.add_argument(
            "--shop",
            type=int,
            help="Branch id (optional instead of --shop-name).",
        )
        parser.add_argument(
            "--all",
            action="store_true",
            help="Show stock value for every branch.",
        )

    def handle(self, *args, **options):
        shop_id = options.get("shop")
        shop_name = (options.get("shop_name") or "").strip()
        show_all = options.get("all")

        if show_all:
            shops = Shop.objects.all().order_by("name")
        elif shop_id:
            shops = Shop.objects.filter(pk=shop_id)
        else:
            shops = Shop.objects.filter(name__iexact=shop_name)

        if not shops.exists():
            self.stderr.write(self.style.ERROR("Shop not found."))
            return

        for shop in shops:
            summary = self._summary(shop.id)
            self.stdout.write("")
            self.stdout.write(self.style.NOTICE(f"=== {shop.name} (id={shop.id}) ==="))
            self.stdout.write(f"Stock Items (products): {summary['items']}")
            self.stdout.write(f"Total Available Qty:    {summary['qty']}")
            if not summary["values"]:
                self.stdout.write("Total Stock Value:      0.00")
            else:
                self.stdout.write("Total Stock Value:")
                for code, amount in summary["values"]:
                    self.stdout.write(f"  {code}: {amount}")

        self.stdout.write("")

    def _summary(self, shop_id):
        product_ids = set()
        total_qty = Decimal("0")
        totals = {}

        stocks = (
            Stock.objects.filter(
                shop_id=shop_id,
                is_deleted=False,
                quantity__gt=0,
                purchase_item__isnull=False,
                purchase_item__is_deleted=False,
                purchase_item__purchase__is_deleted=False,
            )
            .select_related(
                "purchase_item",
                "purchase_item__product",
                "purchase_item__currency",
                "purchase_item__purchase__currency",
            )
        )

        for stock in stocks:
            qty = Decimal(str(stock.quantity or 0))
            if qty <= 0:
                continue
            if stock.purchase_item and stock.purchase_item.product_id:
                product_ids.add(stock.purchase_item.product_id)
            total_qty += qty
            code = normalize_currency_code(
                stock.currency.title if stock.currency else ""
            )
            if not code:
                code = "UNKNOWN"
            price = Decimal(str(stock.average_buy_price or 0))
            totals[code] = totals.get(code, Decimal("0")) + (qty * price)

        values = [
            (
                code,
                amount.quantize(TWOPLACES, rounding=ROUND_HALF_UP),
            )
            for code, amount in sorted(totals.items())
        ]
        return {
            "items": len(product_ids),
            "qty": total_qty,
            "values": values,
        }
