"""Módulo de finanzas — dashboard ejecutivo y gastos operativos.

Endpoints:
    GET  /admin/finance/summary           — P&L del período (default: mes actual)
    GET  /admin/finance/monthly-series    — evolución últimos N meses
    GET  /admin/finance/cash-by-method    — caja por método de pago del período
    GET  /admin/expenses                  — listar gastos
    POST /admin/expenses                  — crear gasto
    PUT  /admin/expenses/<id>             — editar
    DELETE /admin/expenses/<id>           — borrar
    GET  /admin/expenses/categories       — categorías sugeridas + las usadas
"""
from datetime import date, datetime, timezone, timedelta
from decimal import Decimal

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

from ...permissions import require_permission
from ...extensions import db
from ...models import (
    AccountPayable,
    AccountReceivable,
    CommissionStatus,
    OperatingExpense,
    PayableStatus,
    Payment,
    PaymentMethod,
    PaymentStatus,
    ProductItem,
    ReceivableStatus,
    Sale,
    SaleChannel,
    SaleStatus,
    TechnicalService,
    User,
    VendorCommission,
    VendorPayout,
)
from ...utils import get_or_404, paginate
from . import admin_bp


SUGGESTED_CATEGORIES = [
    "alquiler",
    "sueldos",
    "servicios",
    "marketing",
    "mantenimiento",
    "transporte",
    "impuestos",
    "otros",
]


def _money(v):
    return str((v if v is not None else Decimal("0.00")).quantize(Decimal("0.01"))
               if hasattr(v, "quantize") else Decimal(str(v or 0)).quantize(Decimal("0.01")))


def _parse_date(s: str | None, default: date) -> date:
    if not s:
        return default
    try:
        return datetime.strptime(s, "%Y-%m-%d").date()
    except ValueError:
        return default


def _period_from_request() -> tuple[date, date]:
    """Lee `from` y `to` del querystring; default = mes actual."""
    today = date.today()
    month_start = today.replace(day=1)
    f = _parse_date(request.args.get("from"), month_start)
    t = _parse_date(request.args.get("to"), today)
    if t < f:
        t = f
    return f, t


# ────────────────────────────────────────────────────────────────────
# SUMMARY — P&L del período
# ────────────────────────────────────────────────────────────────────

@admin_bp.get("/finance/summary")
@require_permission("finance.view")
def finance_summary():
    f, t = _period_from_request()

    # ── INGRESOS ──
    # Ventas confirmadas en el período (todo canal).
    # La base de cuentas es el SUBTOTAL: los recargos/descuentos son fees del
    # método de pago y NO son ganancia, por eso `sales_total` = subtotal.
    # Recargo/descuento por venta = total − subtotal (se separa con GREATEST).
    sales_q = db.session.query(
        func.count(Sale.id),
        func.coalesce(func.sum(Sale.subtotal), 0),
        func.coalesce(func.sum(Sale.total), 0),
        func.coalesce(func.sum(func.greatest(Sale.total - Sale.subtotal, 0)), 0),
        func.coalesce(func.sum(func.greatest(Sale.subtotal - Sale.total, 0)), 0),
    ).filter(
        Sale.status == SaleStatus.CONFIRMED,
        func.date(Sale.created_at).between(f, t),
    ).one()
    sales_count = sales_q[0]
    sales_subtotal = Decimal(str(sales_q[1] or 0))
    sales_charged = Decimal(str(sales_q[2] or 0))
    sales_surcharge = Decimal(str(sales_q[3] or 0))
    sales_discount = Decimal(str(sales_q[4] or 0))
    # Base de cuentas / ganancia = subtotal (sin fees).
    sales_total = sales_subtotal

    # Pagos efectivamente recibidos en el período (caja entrante).
    payments_in_q = db.session.query(
        func.coalesce(func.sum(Payment.amount), 0),
    ).filter(
        Payment.account_receivable_id.isnot(None),
        func.date(Payment.paid_at).between(f, t),
    ).scalar() or Decimal("0")

    # ── COSTO DE MERCADERÍA VENDIDA (COGS) ──
    # COGS aproximado = suma de cost de los product_items vendidos en
    # ventas confirmadas del período. Si el cost del item está en NULL,
    # ese item no contribuye (asumimos 0 para evitar inflar costos).
    from ...models import SaleItem
    cogs = (
        db.session.query(func.coalesce(func.sum(ProductItem.cost), 0))
        .join(SaleItem, SaleItem.product_item_id == ProductItem.id)
        .join(Sale, Sale.id == SaleItem.sale_id)
        .filter(
            Sale.status == SaleStatus.CONFIRMED,
            func.date(Sale.created_at).between(f, t),
        )
        .scalar()
    ) or Decimal("0")
    cogs = Decimal(str(cogs))

    # ── EGRESOS ──
    # Pagos a proveedores en el período.
    supplier_payments = db.session.query(
        func.coalesce(func.sum(Payment.amount), 0),
    ).filter(
        Payment.account_payable_id.isnot(None),
        func.date(Payment.paid_at).between(f, t),
    ).scalar() or Decimal("0")
    supplier_payments = Decimal(str(supplier_payments))

    # Pagos a técnicos en el período.
    from ...models import TechnicalServicePayment
    tech_payouts = db.session.query(
        func.coalesce(func.sum(TechnicalServicePayment.amount), 0),
    ).filter(
        TechnicalServicePayment.reversed_at.is_(None),
        func.date(TechnicalServicePayment.paid_at).between(f, t),
    ).scalar() or Decimal("0")
    tech_payouts = Decimal(str(tech_payouts))

    # Pagos a vendedores en el período.
    vendor_payouts = db.session.query(
        func.coalesce(func.sum(VendorPayout.amount), 0),
    ).filter(
        VendorPayout.reversed_at.is_(None),
        func.date(VendorPayout.paid_at).between(f, t),
    ).scalar() or Decimal("0")
    vendor_payouts = Decimal(str(vendor_payouts))

    # Gastos operativos del período.
    op_expenses_q = db.session.query(
        OperatingExpense.category,
        func.coalesce(func.sum(OperatingExpense.amount), 0),
    ).filter(
        OperatingExpense.paid_at.between(f, t),
    ).group_by(OperatingExpense.category).all()
    op_expenses_by_cat = {row[0]: str(Decimal(str(row[1]))) for row in op_expenses_q}
    op_expenses_total = sum((Decimal(str(row[1])) for row in op_expenses_q), Decimal("0"))

    # Comisiones devengadas (sin importar si están pagadas).
    commissions_accrued = db.session.query(
        func.coalesce(func.sum(VendorCommission.amount), 0),
    ).filter(
        VendorCommission.status != CommissionStatus.REVERSED,
        func.date(VendorCommission.created_at).between(f, t),
    ).scalar() or Decimal("0")
    commissions_accrued = Decimal(str(commissions_accrued))

    # ── UTILIDADES ──
    gross_profit = sales_total - cogs
    # Utilidad neta: ingresos confirmados − COGS − gastos op − comisiones devengadas.
    # No restamos pagos a proveedores ni payouts porque ya están contabilizados
    # como COGS (proveedores) o comisiones (vendedores). El P&L se basa en
    # devengado, no en caja.
    net_profit = gross_profit - op_expenses_total - commissions_accrued

    # ── BALANCES AL CIERRE DEL PERÍODO ──
    today = date.today()
    ar_q = db.session.query(
        func.count(AccountReceivable.id),
        func.coalesce(func.sum(AccountReceivable.total - AccountReceivable.paid), 0),
    ).filter(
        AccountReceivable.status.in_([ReceivableStatus.PENDING, ReceivableStatus.PARTIAL]),
    ).one()
    ar_overdue = AccountReceivable.query.filter(
        AccountReceivable.status.in_([ReceivableStatus.PENDING, ReceivableStatus.PARTIAL]),
        AccountReceivable.due_date.isnot(None),
        AccountReceivable.due_date < today,
    ).count()

    ap_q = db.session.query(
        func.count(AccountPayable.id),
        func.coalesce(func.sum(AccountPayable.total - AccountPayable.paid), 0),
    ).filter(
        AccountPayable.status.in_([PayableStatus.PENDING, PayableStatus.PARTIAL]),
    ).one()
    ap_overdue = AccountPayable.query.filter(
        AccountPayable.status.in_([PayableStatus.PENDING, PayableStatus.PARTIAL]),
        AccountPayable.due_date.isnot(None),
        AccountPayable.due_date < today,
    ).count()

    return jsonify(
        period={"from": f.isoformat(), "to": t.isoformat()},
        income={
            "sales_count": sales_count,
            # `sales_total` = subtotal (base de cuentas, sin recargos/descuentos).
            "sales_total": _money(sales_total),
            "sales_subtotal": _money(sales_subtotal),
            "sales_surcharge": _money(sales_surcharge),
            "sales_discount": _money(sales_discount),
            "sales_charged": _money(sales_charged),
            "payments_received": _money(payments_in_q),
        },
        cogs=_money(cogs),
        gross_profit=_money(gross_profit),
        operating_expenses={
            "total": _money(op_expenses_total),
            "by_category": op_expenses_by_cat,
        },
        commissions_accrued=_money(commissions_accrued),
        net_profit=_money(net_profit),
        cash_out={
            "supplier_payments": _money(supplier_payments),
            "technician_payouts": _money(tech_payouts),
            "vendor_payouts": _money(vendor_payouts),
            "operating_expenses": _money(op_expenses_total),
            "total": _money(supplier_payments + tech_payouts + vendor_payouts + op_expenses_total),
        },
        receivables={
            "count": ar_q[0],
            "total": _money(ar_q[1]),
            "overdue_count": ar_overdue,
        },
        payables={
            "count": ap_q[0],
            "total": _money(ap_q[1]),
            "overdue_count": ap_overdue,
        },
    )


@admin_bp.get("/finance/monthly-series")
@require_permission("finance.view")
def finance_monthly_series():
    """Evolución de ingresos / egresos / utilidad de los últimos N meses (default 6)."""
    try:
        months = max(1, min(24, int(request.args.get("months", 6))))
    except ValueError:
        months = 6

    today = date.today()
    # Inicio del mes hace N-1 meses (para incluir el actual).
    series = []
    for i in range(months - 1, -1, -1):
        # Calcular el primer y último día del mes (i meses atrás).
        y = today.year
        m = today.month - i
        while m <= 0:
            m += 12
            y -= 1
        start = date(y, m, 1)
        if m == 12:
            end = date(y + 1, 1, 1) - timedelta(days=1)
        else:
            end = date(y, m + 1, 1) - timedelta(days=1)

        # Base de cuentas = subtotal (sin recargos/descuentos).
        sales_total = db.session.query(
            func.coalesce(func.sum(Sale.subtotal), 0),
        ).filter(
            Sale.status == SaleStatus.CONFIRMED,
            func.date(Sale.created_at).between(start, end),
        ).scalar() or Decimal("0")

        op_expenses = db.session.query(
            func.coalesce(func.sum(OperatingExpense.amount), 0),
        ).filter(OperatingExpense.paid_at.between(start, end)).scalar() or Decimal("0")

        commissions = db.session.query(
            func.coalesce(func.sum(VendorCommission.amount), 0),
        ).filter(
            VendorCommission.status != CommissionStatus.REVERSED,
            func.date(VendorCommission.created_at).between(start, end),
        ).scalar() or Decimal("0")

        # COGS aprox
        from ...models import SaleItem
        cogs = (
            db.session.query(func.coalesce(func.sum(ProductItem.cost), 0))
            .join(SaleItem, SaleItem.product_item_id == ProductItem.id)
            .join(Sale, Sale.id == SaleItem.sale_id)
            .filter(
                Sale.status == SaleStatus.CONFIRMED,
                func.date(Sale.created_at).between(start, end),
            )
            .scalar()
        ) or Decimal("0")

        income = Decimal(str(sales_total))
        cogs_d = Decimal(str(cogs))
        opex = Decimal(str(op_expenses))
        comm = Decimal(str(commissions))
        net = income - cogs_d - opex - comm

        series.append({
            "year": y,
            "month": m,
            "label": f"{y}-{m:02d}",
            "income": _money(income),
            "cogs": _money(cogs_d),
            "operating_expenses": _money(opex),
            "commissions": _money(comm),
            "net_profit": _money(net),
        })

    return jsonify(items=series)


@admin_bp.get("/finance/cash-by-method")
@require_permission("finance.view")
def finance_cash_by_method():
    """Pagos recibidos del período agrupados por método de pago."""
    f, t = _period_from_request()
    rows = (
        db.session.query(
            PaymentMethod.id, PaymentMethod.name, PaymentMethod.code,
            func.coalesce(func.sum(Payment.amount), 0),
            func.count(Payment.id),
        )
        .outerjoin(PaymentMethod, PaymentMethod.id == Payment.payment_method_id)
        .filter(
            Payment.account_receivable_id.isnot(None),
            func.date(Payment.paid_at).between(f, t),
        )
        .group_by(PaymentMethod.id, PaymentMethod.name, PaymentMethod.code)
        .order_by(func.coalesce(func.sum(Payment.amount), 0).desc())
        .all()
    )
    return jsonify(items=[
        {
            "method_id": r[0],
            "method_name": r[1] or "(sin método)",
            "method_code": r[2],
            "total": _money(r[3]),
            "count": r[4],
        }
        for r in rows
    ])


# ────────────────────────────────────────────────────────────────────
# GASTOS OPERATIVOS — CRUD
# ────────────────────────────────────────────────────────────────────

def _expense_dump(e: OperatingExpense) -> dict:
    return {
        "id": e.id,
        "category": e.category,
        "description": e.description,
        "amount": _money(e.amount),
        "currency": e.currency,
        "paid_at": e.paid_at.isoformat() if e.paid_at else None,
        "payment_method_id": e.payment_method_id,
        "payment_method": {"id": e.payment_method.id, "name": e.payment_method.name} if e.payment_method else None,
        "reference": e.reference,
        "attachment_url": e.attachment_url,
        "notes": e.notes,
        "user": {"id": e.user.id, "full_name": e.user.full_name} if e.user else None,
        "created_at": e.created_at.isoformat() if e.created_at else None,
    }


@admin_bp.get("/expenses")
@require_permission("expenses.view")
def list_expenses():
    q = OperatingExpense.query.order_by(OperatingExpense.paid_at.desc(), OperatingExpense.id.desc())
    if cat := request.args.get("category"):
        q = q.filter(OperatingExpense.category == cat)
    if frm := request.args.get("from"):
        try:
            q = q.filter(OperatingExpense.paid_at >= datetime.strptime(frm, "%Y-%m-%d").date())
        except ValueError:
            pass
    if to := request.args.get("to"):
        try:
            q = q.filter(OperatingExpense.paid_at <= datetime.strptime(to, "%Y-%m-%d").date())
        except ValueError:
            pass
    # Suma total respetando los mismos filtros que el listado paginado.
    total_q = db.session.query(func.coalesce(func.sum(OperatingExpense.amount), 0))
    if cat := request.args.get("category"):
        total_q = total_q.filter(OperatingExpense.category == cat)
    if frm := request.args.get("from"):
        try:
            total_q = total_q.filter(OperatingExpense.paid_at >= datetime.strptime(frm, "%Y-%m-%d").date())
        except ValueError:
            pass
    if to := request.args.get("to"):
        try:
            total_q = total_q.filter(OperatingExpense.paid_at <= datetime.strptime(to, "%Y-%m-%d").date())
        except ValueError:
            pass
    total_amount = total_q.scalar() or Decimal("0")
    page = paginate(q, default_per_page=50)
    page["items"] = [_expense_dump(e) for e in page["items"]]
    page["total_amount"] = _money(total_amount)
    return jsonify(page)


@admin_bp.post("/expenses")
@require_permission("expenses.create")
def create_expense():
    body = request.get_json(silent=True) or {}
    if not body.get("description") or not body.get("amount") or not body.get("category"):
        return jsonify(error="description, amount y category son requeridos"), 400
    try:
        amount = Decimal(str(body["amount"]))
    except Exception:
        return jsonify(error="amount inválido"), 400
    if amount <= 0:
        return jsonify(error="amount debe ser > 0"), 400

    paid_at = _parse_date(body.get("paid_at"), date.today())
    pm_id = body.get("payment_method_id")
    if pm_id:
        get_or_404(PaymentMethod, int(pm_id))

    e = OperatingExpense(
        category=body["category"].strip().lower(),
        description=body["description"].strip()[:255],
        amount=amount,
        currency=(body.get("currency") or "USD").upper(),
        paid_at=paid_at,
        payment_method_id=int(pm_id) if pm_id else None,
        reference=(body.get("reference") or None),
        attachment_url=(body.get("attachment_url") or None),
        notes=(body.get("notes") or None),
        user_id=current_user.id,
    )
    db.session.add(e)
    db.session.commit()
    return _expense_dump(e), 201


@admin_bp.put("/expenses/<int:expense_id>")
@require_permission("expenses.create")
def update_expense(expense_id):
    e = get_or_404(OperatingExpense, expense_id)
    body = request.get_json(silent=True) or {}
    if "category" in body and body["category"]:
        e.category = body["category"].strip().lower()
    if "description" in body and body["description"]:
        e.description = body["description"].strip()[:255]
    if "amount" in body and body["amount"]:
        try:
            v = Decimal(str(body["amount"]))
            if v > 0:
                e.amount = v
        except Exception:
            pass
    if "paid_at" in body and body["paid_at"]:
        d = _parse_date(body["paid_at"], e.paid_at)
        e.paid_at = d
    if "payment_method_id" in body:
        e.payment_method_id = int(body["payment_method_id"]) if body["payment_method_id"] else None
    for f in ("reference", "attachment_url", "notes"):
        if f in body:
            setattr(e, f, body[f] or None)
    db.session.commit()
    return _expense_dump(e)


@admin_bp.delete("/expenses/<int:expense_id>")
@require_permission("expenses.delete")
def delete_expense(expense_id):
    e = get_or_404(OperatingExpense, expense_id)
    db.session.delete(e)
    db.session.commit()
    return "", 204


@admin_bp.get("/expenses/categories")
@require_permission("expenses.view")
def expense_categories():
    """Categorías sugeridas + las que ya hay cargadas en BD."""
    used = [
        row[0] for row in db.session.query(OperatingExpense.category)
        .distinct().order_by(OperatingExpense.category).all()
    ]
    merged = sorted(set(SUGGESTED_CATEGORIES + used))
    return jsonify(items=merged, suggested=SUGGESTED_CATEGORIES)
