"""Aging / rotación de inventario: qué se vende menos y qué lleva más tiempo parado.

Dos vistas:
  - `/inventory/aging`            -> ranking de productos por "días sin venta".
  - `/inventory/aging/<id>/units` -> antigüedad por unidad (serial) de un producto.

Semáforo (mismos umbrales en ambas): > 60 días rojo, 30-60 amarillo, < 30 verde.
"""
from datetime import datetime, timedelta
from decimal import Decimal

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

from ...permissions import can_see_cost, require_permission
from ...extensions import db
from ...models import (
    ItemStatus,
    Product,
    ProductItem,
    Sale,
    SaleItem,
    SaleStatus,
    Store,
)
from ...utils import get_or_404
from . import admin_bp

# Umbrales del semáforo (días).
AGING_YELLOW_DAYS = 30
AGING_RED_DAYS = 60
_THRESHOLDS = {"yellow": AGING_YELLOW_DAYS, "red": AGING_RED_DAYS}


def _now():
    # Los datetime se guardan naive en UTC; comparamos contra un naive UTC.
    return datetime.utcnow()


def _naive(dt):
    return dt.replace(tzinfo=None) if (dt is not None and dt.tzinfo is not None) else dt


def _days_since(dt):
    dt = _naive(dt)
    if dt is None:
        return None
    return max((_now() - dt).days, 0)


def _color(days):
    if days is None:
        return "green"
    if days > AGING_RED_DAYS:
        return "red"
    if days >= AGING_YELLOW_DAYS:
        return "yellow"
    return "green"


def _money(v):
    return str((v if isinstance(v, Decimal) else Decimal(str(v or 0))).quantize(Decimal("0.01")))


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


@admin_bp.get("/inventory/aging")
@require_permission("stock.view")
def inventory_aging():
    """Ranking de inventario de lenta rotación (lo que menos se vende arriba).

    Por cada producto CON stock disponible calcula hace cuántos días fue su
    última venta; si nunca se vendió, cuántos días lleva la unidad más vieja en
    stock. Ordena del más "frío" (más días sin vender) al más caliente.

    Filtros (query string): q (nombre/sku), store_id, category_id.
    """
    show_cost = can_see_cost(current_user)
    store_id = request.args.get("store_id", type=int)
    category_id = request.args.get("category_id", type=int)
    q = (request.args.get("q") or "").strip().lower()

    # --- Stock disponible por producto (solo AVAILABLE) ---
    avail_q = (
        db.session.query(
            ProductItem.product_id.label("pid"),
            func.count(ProductItem.id).label("available_total"),
            func.min(ProductItem.created_at).label("first_stock_at"),
            func.coalesce(func.sum(ProductItem.cost), 0).label("cost_sum"),
        )
        .filter(ProductItem.status == ItemStatus.AVAILABLE)
    )
    if store_id:
        avail_q = avail_q.filter(ProductItem.store_id == store_id)
    avail_by_pid = {r.pid: r for r in avail_q.group_by(ProductItem.product_id).all()}

    if not avail_by_pid:
        return jsonify(
            items=[], stores=_stores(), show_cost=show_cost, thresholds=_THRESHOLDS,
            totals={"products": 0, "red": 0, "yellow": 0, "green": 0,
                    "available_units": 0, "dead_value": _money(0) if show_cost else None},
        )

    pids = list(avail_by_pid.keys())

    # --- Ventas por producto (unidades reales, ventas no canceladas) ---
    cutoff90 = _now() - timedelta(days=90)
    sales_q = (
        db.session.query(
            SaleItem.product_id.label("pid"),
            func.max(Sale.created_at).label("last_sale_at"),
            func.count(SaleItem.id).label("sold_total"),
            func.coalesce(
                func.sum(case((Sale.created_at >= cutoff90, 1), else_=0)), 0
            ).label("sold_90"),
        )
        .join(Sale, Sale.id == SaleItem.sale_id)
        .filter(SaleItem.product_item_id.isnot(None))
        .filter(SaleItem.product_id.in_(pids))
        .filter(Sale.status != SaleStatus.CANCELLED)
        .group_by(SaleItem.product_id)
    )
    sales_by_pid = {r.pid: r for r in sales_q.all()}

    # --- Info de producto ---
    prod_q = Product.query.filter(Product.id.in_(pids))
    if category_id:
        prod_q = prod_q.filter(Product.category_id == category_id)

    items = []
    for p in prod_q.all():
        av = avail_by_pid.get(p.id)
        if not av:
            continue
        sl = sales_by_pid.get(p.id)
        last_sale_at = sl.last_sale_at if sl else None
        never_sold = last_sale_at is None
        # Días sin venta: desde la última venta; si nunca se vendió, desde que
        # entró la unidad más vieja (lleva ese tiempo sin venderse nunca).
        days_no_sale = _days_since(last_sale_at) if last_sale_at else _days_since(av.first_stock_at)
        # Un producto que NUNCA se ha vendido es inventario parado por
        # definición: siempre rojo, aunque lleve pocos días en stock.
        color = "red" if never_sold else _color(days_no_sale)
        cost_sum = Decimal(str(av.cost_sum or 0))
        items.append({
            "id": p.id,
            "name": p.name,
            "sku": p.sku,
            "image_url": p.image_url,
            "category": p.category.name if p.category else None,
            "available_total": int(av.available_total or 0),
            "sold_total": int(sl.sold_total) if sl else 0,
            "sold_90": int(sl.sold_90) if sl else 0,
            "last_sale_at": last_sale_at.isoformat() if last_sale_at else None,
            "never_sold": never_sold,
            "days_no_sale": days_no_sale,
            "oldest_unit_days": _days_since(av.first_stock_at),
            "color": color,
            "available_value": _money(cost_sum) if show_cost else None,
            "_cost": cost_sum,
        })

    if q:
        items = [it for it in items if q in (it["name"] or "").lower() or q in (it["sku"] or "").lower()]

    # Orden por defecto: más días sin venta primero (lo que menos se vende).
    items.sort(key=lambda it: it["days_no_sale"] if it["days_no_sale"] is not None else 10 ** 9, reverse=True)

    dead_value = sum((it["_cost"] for it in items if it["color"] == "red"), Decimal("0"))
    never_value = sum((it["_cost"] for it in items if it["never_sold"]), Decimal("0"))
    totals = {
        "products": len(items),
        "red": sum(1 for it in items if it["color"] == "red"),
        "yellow": sum(1 for it in items if it["color"] == "yellow"),
        "green": sum(1 for it in items if it["color"] == "green"),
        "available_units": sum(it["available_total"] for it in items),
        "dead_value": _money(dead_value) if show_cost else None,
        # Productos que NUNCA se han vendido: cuántos, cuántas unidades en stock
        # y cuánto dinero representa ese inventario (costo).
        "never_sold": sum(1 for it in items if it["never_sold"]),
        "never_sold_units": sum(it["available_total"] for it in items if it["never_sold"]),
        "never_sold_value": _money(never_value) if show_cost else None,
    }
    for it in items:
        it.pop("_cost", None)

    return jsonify(items=items, stores=_stores(), totals=totals,
                   show_cost=show_cost, thresholds=_THRESHOLDS)


@admin_bp.get("/inventory/aging/<int:product_id>/units")
@require_permission("stock.view")
def inventory_aging_units(product_id):
    """Antigüedad por unidad (serial) de un producto.

    - AVAILABLE: días en stock desde que entró (hoy - created_at).
    - SOLD:      días que tardó en venderse (fecha de venta - created_at).

    Filtros: q (serial/imei), status ('available' por defecto, 'sold', 'all', ...).
    """
    show_cost = can_see_cost(current_user)
    product = get_or_404(Product, product_id)
    status_filter = (request.args.get("status") or "available").lower()
    q = (request.args.get("q") or "").strip().lower()

    units_q = ProductItem.query.filter(ProductItem.product_id == product_id)
    if status_filter and status_filter != "all":
        try:
            units_q = units_q.filter(ProductItem.status == ItemStatus(status_filter))
        except ValueError:
            pass
    units = units_q.all()

    # Fecha de venta por unidad vendida (SaleItem -> Sale.created_at).
    sold_ids = [u.id for u in units if u.status == ItemStatus.SOLD]
    sold_at_by_item = {}
    if sold_ids:
        rows = (
            db.session.query(SaleItem.product_item_id, func.max(Sale.created_at))
            .join(Sale, Sale.id == SaleItem.sale_id)
            .filter(SaleItem.product_item_id.in_(sold_ids))
            .filter(Sale.status != SaleStatus.CANCELLED)
            .group_by(SaleItem.product_item_id)
            .all()
        )
        sold_at_by_item = {pid: dt for pid, dt in rows}

    out = []
    for u in units:
        st = u.status.value if hasattr(u.status, "value") else u.status
        if u.status == ItemStatus.SOLD:
            sold_at = sold_at_by_item.get(u.id)
            days = None
            if sold_at is not None and u.created_at is not None:
                days = max((_naive(sold_at) - _naive(u.created_at)).days, 0)
            out.append({
                "id": u.id, "serial": u.serial, "imei": u.imei, "barcode": u.barcode,
                "status": st, "store_name": u.store.name if u.store else None,
                "warehouse_name": u.warehouse.name if u.warehouse else None,
                "created_at": u.created_at.isoformat() if u.created_at else None,
                "sold_at": sold_at.isoformat() if sold_at else None,
                "days": days, "days_label": "días en venderse", "color": _color(days),
                "cost": (str(u.cost) if u.cost is not None else None) if show_cost else None,
            })
        else:
            days = _days_since(u.created_at)
            out.append({
                "id": u.id, "serial": u.serial, "imei": u.imei, "barcode": u.barcode,
                "status": st, "store_name": u.store.name if u.store else None,
                "warehouse_name": u.warehouse.name if u.warehouse else None,
                "created_at": u.created_at.isoformat() if u.created_at else None,
                "sold_at": None,
                "days": days, "days_label": "días en stock", "color": _color(days),
                "cost": (str(u.cost) if u.cost is not None else None) if show_cost else None,
            })

    if q:
        out = [x for x in out if q in (x["serial"] or "").lower() or q in ((x["imei"] or "").lower())]

    out.sort(key=lambda x: x["days"] if x["days"] is not None else -1, reverse=True)

    return jsonify(
        product={"id": product.id, "name": product.name, "sku": product.sku},
        items=out, show_cost=show_cost, thresholds=_THRESHOLDS,
    )
