"""Admin: gestión de almacenes (warehouses) y ubicaciones internas."""
from decimal import Decimal

from flask import jsonify, request, send_file
from flask_jwt_extended import current_user
from marshmallow import ValidationError
from sqlalchemy import func
from sqlalchemy.exc import IntegrityError

from ...permissions import can_see_cost, require_permission
from ...extensions import db
from ...models import (
    ItemStatus,
    Product,
    ProductItem,
    Store,
    Warehouse,
    WarehouseLocation,
)
from ...pdf import build_warehouse_inventory_pdf
from ...schemas import WarehouseLocationSchema, WarehouseSchema
from ...utils import get_or_404
from . import admin_bp

_w_schema = WarehouseSchema()
_w_list = WarehouseSchema(many=True)
_l_schema = WarehouseLocationSchema()
_l_list = WarehouseLocationSchema(many=True)


@admin_bp.get("/warehouses")
@require_permission("warehouses.view")
def list_warehouses():
    q = Warehouse.query.order_by(Warehouse.store_id, Warehouse.code)
    if store_id := request.args.get("store_id"):
        q = q.filter(Warehouse.store_id == int(store_id))
    if request.args.get("active") == "true":
        q = q.filter(Warehouse.is_active.is_(True))
    return jsonify(items=_w_list.dump(q.all()))


@admin_bp.get("/warehouses/<int:wh_id>")
@require_permission("warehouses.view")
def get_warehouse(wh_id):
    return _w_schema.dump(get_or_404(Warehouse, wh_id))


@admin_bp.post("/warehouses")
@require_permission("warehouses.manage")
def create_warehouse():
    try:
        data = _w_schema.load(request.get_json(silent=True) or {})
    except ValidationError as err:
        return jsonify(errors=err.messages), 400

    get_or_404(Store, data["store_id"])

    # Si is_default = true, desmarcar el resto del mismo store
    if data.get("is_default"):
        Warehouse.query.filter_by(store_id=data["store_id"], is_default=True).update({"is_default": False})

    wh = Warehouse(
        store_id=data["store_id"],
        code=data["code"].strip().upper(),
        name=data["name"].strip(),
        is_default=data.get("is_default", False),
        is_active=data.get("is_active", True),
        notes=data.get("notes"),
    )
    db.session.add(wh)
    try:
        db.session.commit()
    except IntegrityError:
        db.session.rollback()
        return jsonify(error="ya existe un almacén con ese código en esta sede"), 409
    return _w_schema.dump(wh), 201


@admin_bp.put("/warehouses/<int:wh_id>")
@require_permission("warehouses.manage")
def update_warehouse(wh_id):
    wh = get_or_404(Warehouse, wh_id)
    try:
        data = _w_schema.load(request.get_json(silent=True) or {}, partial=True)
    except ValidationError as err:
        return jsonify(errors=err.messages), 400

    if "store_id" in data and data["store_id"] != wh.store_id:
        return jsonify(error="no se puede mover un almacén a otra sede"), 400

    if data.get("is_default"):
        Warehouse.query.filter(
            Warehouse.store_id == wh.store_id, Warehouse.id != wh.id, Warehouse.is_default.is_(True)
        ).update({"is_default": False})

    for k, v in data.items():
        if k == "code" and v:
            v = v.strip().upper()
        if k == "name" and v:
            v = v.strip()
        setattr(wh, k, v)

    try:
        db.session.commit()
    except IntegrityError:
        db.session.rollback()
        return jsonify(error="conflicto de unicidad"), 409
    return _w_schema.dump(wh)


@admin_bp.delete("/warehouses/<int:wh_id>")
@require_permission("warehouses.delete")
def delete_warehouse(wh_id):
    wh = get_or_404(Warehouse, wh_id)
    in_use = ProductItem.query.filter_by(warehouse_id=wh_id).first()
    if in_use:
        # No borrar duro si tiene unidades, sólo desactivar
        wh.is_active = False
        db.session.commit()
        return jsonify(deactivated=True), 200
    db.session.delete(wh)
    db.session.commit()
    return "", 204


# === Ubicaciones internas ===

@admin_bp.get("/warehouses/<int:wh_id>/locations")
@require_permission("warehouses.view")
def list_locations(wh_id):
    get_or_404(Warehouse, wh_id)
    locs = WarehouseLocation.query.filter_by(warehouse_id=wh_id).order_by(WarehouseLocation.code).all()
    return jsonify(items=_l_list.dump(locs))


@admin_bp.post("/warehouses/<int:wh_id>/locations")
@require_permission("warehouses.locations.manage")
def create_location(wh_id):
    get_or_404(Warehouse, wh_id)
    try:
        data = _l_schema.load(request.get_json(silent=True) or {})
    except ValidationError as err:
        return jsonify(errors=err.messages), 400

    loc = WarehouseLocation(
        warehouse_id=wh_id,
        code=data["code"].strip().upper(),
        name=(data.get("name") or "").strip() or None,
        is_active=data.get("is_active", True),
        notes=data.get("notes"),
    )
    db.session.add(loc)
    try:
        db.session.commit()
    except IntegrityError:
        db.session.rollback()
        return jsonify(error="ya existe una ubicación con ese código en este almacén"), 409
    return _l_schema.dump(loc), 201


@admin_bp.put("/warehouses/<int:wh_id>/locations/<int:loc_id>")
@require_permission("warehouses.locations.manage")
def update_location(wh_id, loc_id):
    loc = WarehouseLocation.query.filter_by(id=loc_id, warehouse_id=wh_id).first_or_404()
    try:
        data = _l_schema.load(request.get_json(silent=True) or {}, partial=True)
    except ValidationError as err:
        return jsonify(errors=err.messages), 400

    for k, v in data.items():
        if k == "code" and v:
            v = v.strip().upper()
        if k == "name" and v is not None:
            v = v.strip() or None
        setattr(loc, k, v)
    try:
        db.session.commit()
    except IntegrityError:
        db.session.rollback()
        return jsonify(error="conflicto de unicidad"), 409
    return _l_schema.dump(loc)


@admin_bp.delete("/warehouses/<int:wh_id>/locations/<int:loc_id>")
@require_permission("warehouses.locations.manage")
def delete_location(wh_id, loc_id):
    loc = WarehouseLocation.query.filter_by(id=loc_id, warehouse_id=wh_id).first_or_404()
    in_use = ProductItem.query.filter_by(location_id=loc_id).first()
    if in_use:
        loc.is_active = False
        db.session.commit()
        return jsonify(deactivated=True), 200
    db.session.delete(loc)
    db.session.commit()
    return "", 204


# ============================================================
# Detail (KPIs + items + breakdown) y PDF de inventario
# ============================================================

@admin_bp.get("/warehouses/<int:wh_id>/detail")
@require_permission("warehouses.view")
def warehouse_detail(wh_id):
    """Ficha del almacén: KPIs + breakdown por status + breakdown por producto.

    La valuación al costo (`total_value` / `by_product[].value`) es sensible:
    solo `costs.view` (admin). El resto la recibe en `None`.
    """
    wh = get_or_404(Warehouse, wh_id)
    show_cost = can_see_cost(current_user)

    items = (
        ProductItem.query
        .filter_by(warehouse_id=wh_id)
        .all()
    )

    stats = {s.value: 0 for s in ItemStatus}
    total_value = Decimal("0")
    by_product = {}
    by_location = {}
    products_distinct = set()

    for it in items:
        st = it.status.value if hasattr(it.status, "value") else it.status
        stats[st] = stats.get(st, 0) + 1
        # La valuación cuenta SOLO unidades disponibles (stock real).
        if st == "available" and it.cost:
            total_value += Decimal(it.cost)
        products_distinct.add(it.product_id)

        # por producto (solo disponibles cuentan visualmente en stock)
        pkey = it.product_id
        if pkey not in by_product:
            by_product[pkey] = {
                "product_id": pkey,
                "name": it.product.name if it.product else "—",
                "sku": it.product.sku if it.product else "",
                "image_url": it.product.image_url if it.product else None,
                "total": 0, "available": 0, "sold": 0, "reserved": 0, "other": 0,
                "value": Decimal("0"),
            }
        by_product[pkey]["total"] += 1
        if st == "available": by_product[pkey]["available"] += 1
        elif st == "sold": by_product[pkey]["sold"] += 1
        elif st == "reserved": by_product[pkey]["reserved"] += 1
        else: by_product[pkey]["other"] += 1
        if st == "available" and it.cost:
            by_product[pkey]["value"] += Decimal(it.cost)

        # por ubicación interna
        lkey = it.location_id or 0
        if lkey not in by_location:
            by_location[lkey] = {
                "location_id": it.location_id,
                "code": it.location_ref.code if it.location_ref else None,
                "name": it.location_ref.name if it.location_ref else None,
                "total": 0,
            }
        by_location[lkey]["total"] += 1

    # serializar
    by_product_list = []
    for d in by_product.values():
        d["value"] = str(d["value"]) if show_cost else None
        by_product_list.append(d)
    by_product_list.sort(key=lambda d: -d["total"])

    by_location_list = list(by_location.values())
    by_location_list.sort(key=lambda d: (d["code"] or "zzz"))

    return jsonify(
        warehouse=_w_schema.dump(wh),
        stats={
            **stats,
            "total": len(items),
            "products_distinct": len(products_distinct),
            "total_value": str(total_value) if show_cost else None,
        },
        by_product=by_product_list,
        by_location=by_location_list,
    )


@admin_bp.get("/warehouses/<int:wh_id>/inventory.pdf")
@require_permission("warehouses.inventory_pdf")
def warehouse_inventory_pdf(wh_id):
    wh = get_or_404(Warehouse, wh_id)
    # Reporte de inventario = stock DISPONIBLE: solo unidades AVAILABLE (las
    # vendidas conservan warehouse_id pero ya no son stock).
    items = (
        ProductItem.query
        .filter_by(warehouse_id=wh_id, status=ItemStatus.AVAILABLE)
        .order_by(ProductItem.location_id, ProductItem.serial)
        .all()
    )
    pdf = build_warehouse_inventory_pdf(wh, items, show_cost=can_see_cost(current_user))
    safe = "".join(c if c.isalnum() else "_" for c in (wh.code or f"warehouse-{wh.id}"))
    return send_file(
        pdf,
        mimetype="application/pdf",
        as_attachment=False,
        download_name=f"ChevroCaracas-Inventario-{safe}.pdf",
    )
