"""Auditoría de movimientos de inventario.

Feed unificado de TODOS los movimientos (`StockMovement`) con filtros:
producto, almacén, sede, tipo, usuario, rango de fechas. Pensado para
auditorías y trazabilidad por producto/sede/almacén.
"""
from datetime import datetime, timedelta
from decimal import Decimal

from flask import jsonify, request
from sqlalchemy import desc, func, or_

from ...permissions import require_permission
from ...extensions import db
from ...models import (
    MovementType,
    Product,
    ProductItem,
    StockMovement,
    Store,
    User,
    Warehouse,
)
from ...utils import paginate
from . import admin_bp


def _parse_date(s, end=False):
    if not s:
        return None
    try:
        d = datetime.fromisoformat(s)
        return d + timedelta(days=1) if end else d
    except ValueError:
        return None


@admin_bp.get("/audit/movements")
@require_permission("audit.view")
def audit_movements():
    """Feed paginado y filtrable de stock movements para auditoría."""
    # Joins necesarios para filtros + dump enriquecido
    q = (
        db.session.query(StockMovement)
        .join(ProductItem, ProductItem.id == StockMovement.product_item_id)
        .outerjoin(Product, Product.id == ProductItem.product_id)
    )

    # === Filtros ===
    if pid := request.args.get("product_id"):
        q = q.filter(ProductItem.product_id == int(pid))
    if wh_id := request.args.get("warehouse_id"):
        q = q.filter(ProductItem.warehouse_id == int(wh_id))
    if st_id := request.args.get("store_id"):
        q = q.filter(ProductItem.store_id == int(st_id))
    if mtype := request.args.get("type"):
        q = q.filter(StockMovement.type == mtype)
    if uid := request.args.get("user_id"):
        q = q.filter(StockMovement.user_id == int(uid))
    if ref_type := request.args.get("reference_type"):
        q = q.filter(StockMovement.reference_type == ref_type)
    if df := _parse_date(request.args.get("date_from")):
        q = q.filter(StockMovement.created_at >= df)
    if dt := _parse_date(request.args.get("date_to"), end=True):
        q = q.filter(StockMovement.created_at < dt)
    if search := request.args.get("q"):
        like = f"%{search}%"
        q = q.filter(or_(
            ProductItem.serial.ilike(like),
            ProductItem.barcode.ilike(like),
            Product.name.ilike(like),
            Product.sku.ilike(like),
        ))

    q = q.order_by(desc(StockMovement.created_at))

    page = paginate(q, default_per_page=50)
    items = []
    for m in page["items"]:
        item = m.item
        items.append({
            "id": m.id,
            "type": m.type.value if hasattr(m.type, "value") else m.type,
            "reference_type": m.reference_type,
            "reference_id": m.reference_id,
            "notes": m.notes,
            "created_at": m.created_at.isoformat(),
            "user": {"id": m.user.id, "full_name": m.user.full_name} if m.user else None,
            "item": {
                "id": item.id,
                "serial": item.serial,
                "barcode": item.barcode,
                "imei": item.imei,
                "store": {"id": item.store.id, "code": item.store.code, "name": item.store.name} if item.store else None,
                "warehouse": {
                    "id": item.warehouse.id, "code": item.warehouse.code, "name": item.warehouse.name,
                } if item.warehouse else None,
                "location_ref": {
                    "id": item.location_ref.id, "code": item.location_ref.code,
                } if item.location_ref else None,
                "product": {
                    "id": item.product.id, "name": item.product.name,
                    "sku": item.product.sku, "image_url": item.product.image_url,
                } if item.product else None,
            } if item else None,
        })
    page["items"] = items
    return jsonify(page)


@admin_bp.get("/audit/movements/summary")
@require_permission("audit.view")
def audit_summary():
    """KPIs y agregados rápidos para el dashboard de auditoría (mismos filtros)."""
    base = (
        db.session.query(StockMovement)
        .join(ProductItem, ProductItem.id == StockMovement.product_item_id)
    )

    # Aplicar mismos filtros
    if pid := request.args.get("product_id"):
        base = base.filter(ProductItem.product_id == int(pid))
    if wh_id := request.args.get("warehouse_id"):
        base = base.filter(ProductItem.warehouse_id == int(wh_id))
    if st_id := request.args.get("store_id"):
        base = base.filter(ProductItem.store_id == int(st_id))
    if mtype := request.args.get("type"):
        base = base.filter(StockMovement.type == mtype)
    if uid := request.args.get("user_id"):
        base = base.filter(StockMovement.user_id == int(uid))
    if df := _parse_date(request.args.get("date_from")):
        base = base.filter(StockMovement.created_at >= df)
    if dt := _parse_date(request.args.get("date_to"), end=True):
        base = base.filter(StockMovement.created_at < dt)

    total = base.count()

    # Agrupado por tipo
    by_type = {}
    rows = (
        base.with_entities(StockMovement.type, func.count(StockMovement.id))
        .group_by(StockMovement.type).all()
    )
    for t, c in rows:
        key = t.value if hasattr(t, "value") else t
        by_type[key] = c

    # Top 5 productos con más movimientos
    top_products_rows = (
        base.with_entities(
            Product.id, Product.name, Product.sku,
            func.count(StockMovement.id).label("count"),
        )
        .join(Product, Product.id == ProductItem.product_id)
        .group_by(Product.id, Product.name, Product.sku)
        .order_by(func.count(StockMovement.id).desc())
        .limit(5).all()
    )
    top_products = [
        {"id": r[0], "name": r[1], "sku": r[2], "count": r[3]}
        for r in top_products_rows
    ]

    # Top 5 usuarios
    top_users_rows = (
        base.with_entities(
            User.id, User.full_name,
            func.count(StockMovement.id).label("count"),
        )
        .join(User, User.id == StockMovement.user_id)
        .group_by(User.id, User.full_name)
        .order_by(func.count(StockMovement.id).desc())
        .limit(5).all()
    )
    top_users = [
        {"id": r[0], "full_name": r[1], "count": r[2]}
        for r in top_users_rows
    ]

    return jsonify(
        total=total,
        by_type=by_type,
        top_products=top_products,
        top_users=top_users,
    )