from decimal import Decimal

from flask import jsonify, request
from flask_jwt_extended import current_user
from sqlalchemy import and_, func

from ...permissions import _role_of, can_see_cost, is_allowed, require_permission
from ...extensions import db
from ...models import ItemStatus, Product, ProductItem, Store, Warehouse
from . import admin_bp


def _money(v):
    """Decimal -> string con 2 decimales (o '0.00')."""
    return str((v if isinstance(v, Decimal) else Decimal(str(v or 0))).quantize(Decimal("0.01")))


@admin_bp.get("/stock/global")
@require_permission("stock.view")
def stock_global():
    """Stock por producto con desglose por sede + estado.

    Soporta valuación del inventario disponible: costo (suma de
    `ProductItem.cost`), valor de venta (precio efectivo de cada unidad) y
    ganancia estimada (venta − costo). El COSTO y la GANANCIA (que revela el
    costo) son sensibles: solo `costs.view` (admin). El valor de venta —que no
    es un costo— se muestra a `reports.view` (admin / inventario).

    Filtros (query string):
      - `q`        : busca por nombre o SKU.
      - `store_id` : limita el reporte a una sede (solo productos con unidades
                     en esa sede). Sin él, reporta todas las sedes.
    """
    show_value = is_allowed(_role_of(current_user), "reports.view")
    show_cost = can_see_cost(current_user)

    # Sede opcional: al filtrar por una columna del lado derecho del outer join
    # se descartan los productos sin unidades en esa sede, que es justo lo que
    # se quiere para un reporte por sede.
    store_id = request.args.get("store_id", type=int)

    query = (
        db.session.query(
            Product.id, Product.name, Product.sku, Product.image_url,
            ProductItem.store_id,
            ProductItem.status,
            func.count(ProductItem.id).label("qty"),
            func.coalesce(func.sum(ProductItem.cost), 0).label("cost_sum"),
            func.coalesce(
                func.sum(func.coalesce(ProductItem.sale_price, Product.price)), 0
            ).label("sale_sum"),
        )
        .outerjoin(ProductItem, ProductItem.product_id == Product.id)
        .filter(Product.is_active.is_(True))
    )
    if store_id:
        query = query.filter(ProductItem.store_id == store_id)
    rows = query.group_by(
        Product.id, Product.name, Product.sku, Product.image_url,
        ProductItem.store_id, ProductItem.status,
    ).all()

    products = {}
    for r in rows:
        if r.id not in products:
            products[r.id] = {
                "id": r.id,
                "name": r.name,
                "sku": r.sku,
                "image_url": r.image_url,
                "by_store": {},
                "by_status": {},
                "total": 0,
                "available_total": 0,
                "in_service_total": 0,  # equipos en servicio técnico (no vendibles)
                # Valuación del stock disponible (solo si show_value).
                "_cost": Decimal("0"),
                "_sale": Decimal("0"),
            }
        if r.qty == 0:
            continue
        # El desglose por estado se guarda completo (detalle secundario), pero el
        # STOCK que se muestra (matriz por sede, total, valuación) cuenta SOLO las
        # unidades disponibles. Vendidas/reservadas/servicio/dañadas/perdidas no
        # son stock.
        if r.status is not None:
            status_str = r.status.value if hasattr(r.status, "value") else r.status
            products[r.id]["by_status"][status_str] = products[r.id]["by_status"].get(status_str, 0) + r.qty
        products[r.id]["total"] += r.qty
        if r.status == ItemStatus.AVAILABLE:
            if r.store_id is not None:
                products[r.id]["by_store"][r.store_id] = products[r.id]["by_store"].get(r.store_id, 0) + r.qty
            products[r.id]["available_total"] += r.qty
            products[r.id]["_cost"] += Decimal(str(r.cost_sum or 0))
            products[r.id]["_sale"] += Decimal(str(r.sale_sum or 0))
        elif r.status == ItemStatus.IN_SERVICE:
            products[r.id]["in_service_total"] += r.qty

    stores = Store.query.filter_by(is_active=True).order_by(Store.is_main.desc(), Store.name).all()
    stores_data = [{"id": s.id, "code": s.code, "name": s.name} for s in stores]

    items = list(products.values())
    # No mostrar productos sin stock: solo los que tienen al menos 1 unidad
    # disponible (AVAILABLE). Los agotados / sin stock vendible quedan fuera.
    items = [p for p in items if p["available_total"] > 0]
    if q := request.args.get("q"):
        like = q.lower()
        items = [p for p in items if like in p["name"].lower() or like in p["sku"].lower()]

    items.sort(key=lambda p: p["name"])

    # Totales del reporte (sobre el set filtrado) + serialización de valuación.
    tot_units = sum(p["total"] for p in items)
    tot_available = sum(p["available_total"] for p in items)
    tot_cost = sum((p["_cost"] for p in items), Decimal("0"))
    tot_sale = sum((p["_sale"] for p in items), Decimal("0"))

    for p in items:
        cost, sale = p.pop("_cost"), p.pop("_sale")
        avail = p["available_total"] or 0
        p["cost_value"] = _money(cost) if show_cost else None
        # Costo unitario = costo total disponible / unidades disponibles (solo admin).
        p["unit_cost"] = (_money(cost / avail) if avail else None) if show_cost else None
        p["sale_value"] = _money(sale) if show_value else None
        p["profit"] = _money(sale - cost) if show_cost else None

    totals = {
        "units": tot_units,
        "available": tot_available,
        "cost_value": _money(tot_cost) if show_cost else None,
        "unit_cost": (_money(tot_cost / tot_available) if tot_available else None) if show_cost else None,
        "sale_value": _money(tot_sale) if show_value else None,
        "profit": _money(tot_sale - tot_cost) if show_cost else None,
    }

    return jsonify(
        items=items,
        stores=stores_data,
        totals=totals,
        show_value=show_value,
        show_cost=show_cost,
        store_id=store_id,
    )


@admin_bp.get("/stock/by-warehouse")
@require_permission("stock.view")
def stock_by_warehouse():
    """Vista jerárquica: Sede → Almacén → Producto (cantidad disponible).

    El `value` (valuación al costo) es sensible: solo `costs.view` (admin).
    """
    show_cost = can_see_cost(current_user)
    rows = (
        db.session.query(
            Store.id.label("store_id"), Store.code.label("store_code"), Store.name.label("store_name"),
            Warehouse.id.label("warehouse_id"), Warehouse.code.label("warehouse_code"),
            Warehouse.name.label("warehouse_name"), Warehouse.is_default.label("warehouse_default"),
            Product.id.label("product_id"), Product.name.label("product_name"),
            Product.sku.label("product_sku"), Product.image_url.label("product_image"),
            ProductItem.status,
            func.count(ProductItem.id).label("qty"),
            func.sum(ProductItem.cost).label("value"),
        )
        .select_from(Store)
        .outerjoin(Warehouse, Warehouse.store_id == Store.id)
        # Solo unidades DISPONIBLES entran al árbol de stock. El filtro va en el
        # ON del outer join (no en WHERE) para que los almacenes sin stock
        # disponible sigan apareciendo vacíos en vez de desaparecer.
        .outerjoin(
            ProductItem,
            and_(
                ProductItem.warehouse_id == Warehouse.id,
                ProductItem.status == ItemStatus.AVAILABLE,
            ),
        )
        .outerjoin(Product, Product.id == ProductItem.product_id)
        .filter(Store.is_active.is_(True))
        .group_by(
            Store.id, Store.code, Store.name,
            Warehouse.id, Warehouse.code, Warehouse.name, Warehouse.is_default,
            Product.id, Product.name, Product.sku, Product.image_url,
            ProductItem.status,
        )
        .all()
    )

    # Buildup tree: { store_id: { ..., warehouses: { wh_id: { ..., products: { pid: {...} } } } } }
    tree = {}
    for r in rows:
        sid = r.store_id
        if sid not in tree:
            tree[sid] = {
                "store_id": sid, "code": r.store_code, "name": r.store_name,
                "totals": {"units": 0, "available": 0, "value": Decimal("0")},
                "warehouses": {},
            }
        if r.warehouse_id is None:
            continue
        wid = r.warehouse_id
        if wid not in tree[sid]["warehouses"]:
            tree[sid]["warehouses"][wid] = {
                "warehouse_id": wid, "code": r.warehouse_code, "name": r.warehouse_name,
                "is_default": bool(r.warehouse_default),
                "totals": {"units": 0, "available": 0, "value": Decimal("0")},
                "products": {},
            }
        if r.product_id is None:
            continue
        pid = r.product_id
        if pid not in tree[sid]["warehouses"][wid]["products"]:
            tree[sid]["warehouses"][wid]["products"][pid] = {
                "product_id": pid, "name": r.product_name, "sku": r.product_sku,
                "image_url": r.product_image,
                "by_status": {}, "total": 0, "available": 0, "value": Decimal("0"),
            }
        st = r.status.value if hasattr(r.status, "value") else r.status
        bucket = tree[sid]["warehouses"][wid]["products"][pid]
        bucket["by_status"][st] = bucket["by_status"].get(st, 0) + r.qty
        bucket["total"] += r.qty
        # Stock = solo disponible: conteos (available/units) y valuación (value)
        # cuentan únicamente las unidades AVAILABLE. by_status/total quedan como
        # detalle.
        if st == "available":
            bucket_value = Decimal(r.value) if r.value else Decimal("0")
            bucket["available"] += r.qty
            bucket["value"] += bucket_value
            tree[sid]["warehouses"][wid]["totals"]["available"] += r.qty
            tree[sid]["warehouses"][wid]["totals"]["units"] += r.qty
            tree[sid]["warehouses"][wid]["totals"]["value"] += bucket_value
            tree[sid]["totals"]["available"] += r.qty
            tree[sid]["totals"]["units"] += r.qty
            tree[sid]["totals"]["value"] += bucket_value

    # Serialize. La valuación (`value`) solo se expone si el usuario ve costos.
    out_stores = []
    for sd in sorted(tree.values(), key=lambda x: x["name"]):
        sd["totals"]["value"] = str(sd["totals"]["value"]) if show_cost else None
        whs = []
        for wd in sorted(sd["warehouses"].values(), key=lambda w: (not w["is_default"], w["code"])):
            wd["totals"]["value"] = str(wd["totals"]["value"]) if show_cost else None
            prods = []
            for pd in sorted(wd["products"].values(), key=lambda p: -p["total"]):
                pd["value"] = str(pd["value"]) if show_cost else None
                prods.append(pd)
            wd["products"] = prods
            whs.append(wd)
        sd["warehouses"] = whs
        out_stores.append(sd)

    return jsonify(stores=out_stores, show_cost=show_cost)


@admin_bp.get("/stock/by-product/<int:product_id>")
@require_permission("stock.view")
def stock_by_product(product_id):
    """Detalle: cada unidad de un producto con sede + estado."""
    show_cost = can_see_cost(current_user)
    units = (
        ProductItem.query
        .filter_by(product_id=product_id)
        .order_by(ProductItem.store_id, ProductItem.status, ProductItem.serial)
        .all()
    )
    data = [{
        "id": u.id,
        "serial": u.serial,
        "barcode": u.barcode,
        "imei": u.imei,
        "status": u.status.value if hasattr(u.status, "value") else u.status,
        # Datos propios de la unidad (iPhones usados): color y salud de batería.
        "color": u.color,
        "battery_pct": u.battery_pct,
        "store_id": u.store_id,
        "store_name": u.store.name if u.store else None,
        "location": u.location,
        "cost": (str(u.cost) if u.cost else None) if show_cost else None,
        # Precio individual de la unidad (sale_price si está seteado, sino
        # cae al precio del modelo). Usado por POS / cross-stock para
        # mostrar el precio real que se cobrará.
        "sale_price": str(u.sale_price) if u.sale_price is not None else None,
        "effective_price": str(u.effective_price) if u.effective_price is not None else None,
        "created_at": u.created_at.isoformat(),
    } for u in units]
    return jsonify(items=data)
