"""Presupuestos (cotizaciones).

Endpoints:
    GET    /admin/quotes              — listar
    GET    /admin/quotes/<id>         — detalle
    POST   /admin/quotes              — crear
    DELETE /admin/quotes/<id>         — borrar (admin)
    GET    /admin/quotes/<id>/export.pdf — PDF imprimible
"""
from datetime import datetime
from decimal import Decimal

from flask import jsonify, render_template, request
from flask_jwt_extended import current_user

from ...permissions import require_permission
from ...extensions import db
from ...models import Currency, Customer, PaymentMethod, Product, Quote, QuoteItem
from ...utils import get_or_404, paginate


def _current_ves_rate() -> Decimal | None:
    """Última tasa Bs/USD registrada (cuántos Bs equivalen a 1 USD).

    Devuelve None si no hay moneda VES configurada o si no tiene tasa cargada.
    """
    ves = Currency.query.filter_by(code="VES").first()
    if not ves:
        return None
    rate = ves.current_rate
    return rate if rate is not None else None
from . import admin_bp


def _user_ref(u):
    if u is None:
        return None
    return {"id": u.id, "full_name": u.full_name, "email": u.email}


def _customer_ref(c):
    if c is None:
        return None
    return {
        "id": c.id, "name": c.name, "document": c.document,
        "phone": c.phone, "email": c.email,
    }


def _dump(q: Quote) -> dict:
    # Lectura defensiva: si la migración SQL todavía no corrió en la BD,
    # estas columnas no existen y `getattr` devuelve el default — el
    # endpoint sigue funcionando sin reventar el listado/detalle.
    iva_enabled = bool(getattr(q, "iva_enabled", False))
    iva_percent_val = getattr(q, "iva_percent", None) or Decimal("0")
    exchange_rate_val = getattr(q, "exchange_rate", None)

    iva_amount = Decimal("0.00")
    total_with_iva = q.total
    if iva_enabled and iva_percent_val:
        iva_amount = (q.total * iva_percent_val / Decimal("100")).quantize(Decimal("0.01"))
        total_with_iva = (q.total + iva_amount).quantize(Decimal("0.01"))
    total_bs = None
    iva_bs = None
    total_with_iva_bs = None
    if exchange_rate_val:
        total_bs = (q.total * exchange_rate_val).quantize(Decimal("0.01"))
        if iva_enabled:
            iva_bs = (iva_amount * exchange_rate_val).quantize(Decimal("0.01"))
            total_with_iva_bs = (total_with_iva * exchange_rate_val).quantize(Decimal("0.01"))

    # Vista en la MONEDA del presupuesto: si es en Bs (VES), TODO se muestra en
    # Bs (base USD × tasa snapshot); si es en USD, en USD. El IVA es opcional en
    # ambos. Las vistas usan los campos `display_*` y `display_symbol`.
    currency = (q.currency or "USD").upper()
    is_bs = currency == "VES"
    # El ajuste del método de pago ya viene "plegado" en los precios guardados
    # (se aplica al crear el presupuesto en Bs), así que acá solo se convierte
    # por la tasa. El cliente nunca ve el ajuste como línea.
    disp_mult = exchange_rate_val if (is_bs and exchange_rate_val) else Decimal("1")
    disp_symbol = "Bs" if is_bs else "$"

    def _d(usd) -> str:
        return str((Decimal(str(usd or 0)) * disp_mult).quantize(Decimal("0.01")))

    return {
        "id": q.id,
        "number": q.number,
        "customer_id": q.customer_id,
        "customer": _customer_ref(q.customer),
        "user_id": q.user_id,
        "user": _user_ref(q.user),
        "subtotal": str(q.subtotal),
        "discount": str(q.discount),
        "total": str(q.total),
        "currency": q.currency,
        "iva_enabled": iva_enabled,
        "iva_percent": str(iva_percent_val),
        "iva_amount": str(iva_amount),
        "total_with_iva": str(total_with_iva),
        "exchange_rate": str(exchange_rate_val) if exchange_rate_val else None,
        "total_bs": str(total_bs) if total_bs is not None else None,
        "iva_bs": str(iva_bs) if iva_bs is not None else None,
        "total_with_iva_bs": str(total_with_iva_bs) if total_with_iva_bs is not None else None,
        # Montos ya en la moneda del presupuesto (lo que ve el cliente).
        "display_currency": currency,
        "display_symbol": disp_symbol,
        "display_subtotal": _d(q.subtotal),
        "display_discount": _d(q.discount),
        "display_total": _d(q.total),
        "display_iva": _d(iva_amount),
        "display_total_with_iva": _d(total_with_iva),
        "valid_until": q.valid_until.isoformat() if q.valid_until else None,
        "notes": q.notes,
        "created_at": q.created_at.isoformat() if q.created_at else None,
        "items": [{
            "id": it.id,
            "product_id": it.product_id,
            "product_name": it.product_name,
            "sku": it.sku,
            "quantity": it.quantity,
            "unit_price": str(it.unit_price),
            "line_total": str(it.line_total),
            "display_unit_price": _d(it.unit_price),
            "display_line_total": _d(it.line_total),
            "notes": it.notes,
        } for it in (q.items or [])],
    }


@admin_bp.get("/quotes")
@require_permission("quotes.view")
def list_quotes():
    q = Quote.query.order_by(Quote.created_at.desc())
    if cid := request.args.get("customer_id"):
        try: q = q.filter(Quote.customer_id == int(cid))
        except ValueError: pass
    if search := request.args.get("q"):
        q = q.filter(Quote.number.ilike(f"%{search}%"))
    page = paginate(q)
    page["items"] = [_dump(x) for x in page["items"]]
    return jsonify(page)


@admin_bp.get("/quotes/<int:quote_id>")
@require_permission("quotes.view")
def get_quote(quote_id):
    q = get_or_404(Quote, quote_id)
    return jsonify(_dump(q))


@admin_bp.post("/quotes")
@require_permission("quotes.create")
def create_quote():
    body = request.get_json(silent=True) or {}
    items_in = body.get("items") or []
    if not items_in:
        return jsonify(error="al menos un producto es requerido"), 400

    customer = None
    if cid := body.get("customer_id"):
        customer = get_or_404(Customer, int(cid))

    valid_until = None
    if vu := body.get("valid_until"):
        try:
            valid_until = datetime.strptime(vu, "%Y-%m-%d").date()
        except ValueError:
            return jsonify(error="valid_until debe ser YYYY-MM-DD"), 400

    iva_enabled = bool(body.get("iva_enabled", False))
    try:
        iva_percent = Decimal(str(body.get("iva_percent", "16")))
    except Exception:
        iva_percent = Decimal("16")
    if iva_percent < 0 or iva_percent > 100:
        return jsonify(error="iva_percent debe estar entre 0 y 100"), 400

    # Moneda del presupuesto: USD o VES (Bs). Determina en qué moneda se
    # muestra TODO al cliente.
    currency = (body.get("currency") or "USD").upper()
    is_bs = currency == "VES"

    # Tasa snapshot: si el cliente la envía la usamos; si no, tomamos la
    # vigente. Se congela en el presupuesto para que el monto Bs no cambie
    # cuando varíe la tasa del sistema. Un presupuesto en Bs SIEMPRE requiere
    # tasa (todo se muestra convertido a Bs).
    exchange_rate = None
    if raw_rate := body.get("exchange_rate"):
        try:
            exchange_rate = Decimal(str(raw_rate))
            if exchange_rate <= 0:
                exchange_rate = None
        except Exception:
            exchange_rate = None
    if exchange_rate is None and is_bs:
        exchange_rate = _current_ves_rate()
    if is_bs and (exchange_rate is None or exchange_rate <= 0):
        return jsonify(
            error="Para un presupuesto en Bs cargá la tasa Bs/USD (Configuración → Monedas)."
        ), 400

    quote = Quote(
        number="PENDING",
        customer_id=customer.id if customer else None,
        user_id=current_user.id if current_user else None,
        currency=currency,
        iva_enabled=iva_enabled,
        iva_percent=iva_percent,
        exchange_rate=exchange_rate,
        valid_until=valid_until,
        notes=(body.get("notes") or None),
    )
    db.session.add(quote)
    db.session.flush()
    quote.number = f"COT-{quote.id:06d}"

    # Ajuste del método de pago (solo Bs): se "pliega" en cada precio para que
    # el cliente vea el precio en Bs ya con el ajuste, SIN una línea de recargo.
    price_factor = Decimal("1")
    if is_bs and (pmid := body.get("payment_method_id")):
        try:
            pm = db.session.get(PaymentMethod, int(pmid))
        except (TypeError, ValueError):
            pm = None
        if pm is not None and pm.adjustment_percent:
            price_factor = Decimal("1") + Decimal(str(pm.adjustment_percent)) / Decimal("100")

    subtotal = Decimal("0.00")
    for raw in items_in:
        product_id = raw.get("product_id")
        product = None
        product_name = (raw.get("product_name") or "").strip()
        sku = (raw.get("sku") or "").strip() or None
        if product_id:
            product = db.session.get(Product, int(product_id))
            if product:
                product_name = product_name or product.name
                sku = sku or product.sku
        if not product_name:
            db.session.rollback()
            return jsonify(error="cada línea necesita product_id o product_name"), 400
        try:
            qty = int(raw.get("quantity", 1))
            unit_price = Decimal(str(raw.get("unit_price", "0")))
        except Exception:
            db.session.rollback()
            return jsonify(error="quantity o unit_price inválidos"), 400
        if qty < 1 or unit_price < 0:
            db.session.rollback()
            return jsonify(error="quantity debe ser ≥ 1 y unit_price ≥ 0"), 400
        # Precio ya "con ajuste" del método de pago (Bs). En $ price_factor = 1.
        unit_price = (unit_price * price_factor).quantize(Decimal("0.01"))
        line = (unit_price * qty).quantize(Decimal("0.01"))
        db.session.add(QuoteItem(
            quote_id=quote.id,
            product_id=product.id if product else None,
            product_name=product_name,
            sku=sku,
            quantity=qty,
            unit_price=unit_price,
            line_total=line,
            notes=(raw.get("notes") or None),
        ))
        subtotal += line

    try:
        discount = Decimal(str(body.get("discount", "0")))
    except Exception:
        discount = Decimal("0")
    if discount < 0:
        discount = Decimal("0")
    total = max(subtotal - discount, Decimal("0.00")).quantize(Decimal("0.01"))

    quote.subtotal = subtotal
    quote.discount = discount
    quote.total = total
    db.session.commit()
    return _dump(quote), 201


@admin_bp.delete("/quotes/<int:quote_id>")
@require_permission("quotes.delete")
def delete_quote(quote_id):
    q = get_or_404(Quote, quote_id)
    db.session.delete(q)
    db.session.commit()
    return "", 204


@admin_bp.get("/quotes/_meta")
@require_permission("quotes.view")
def quotes_meta():
    """Devuelve la tasa Bs/USD vigente para precargarla en el form."""
    rate = _current_ves_rate()
    return jsonify(exchange_rate=str(rate) if rate is not None else None)


@admin_bp.get("/quotes/<int:quote_id>/export.pdf")
@require_permission("quotes.view")
def export_quote_pdf(quote_id):
    """Devuelve el presupuesto renderizado como HTML imprimible.

    En vez de generar un PDF binario en el servidor (reportlab + Pillow,
    pesado y propenso a fallar en hosting compartido), servimos un HTML
    con marca NES y un botón "Imprimir / Guardar PDF" que dispara el
    diálogo de impresión del navegador. El usuario elige "Guardar como PDF"
    desde ahí — funciona en cualquier hosting porque no usa libs nativas.
    """
    q = get_or_404(Quote, quote_id)
    html = render_template(
        "pdf/quote.html",
        q=q,
        doc_title="Presupuesto",
        doc_subtitle=q.number,
        generated_at=datetime.utcnow().strftime("%Y-%m-%d %H:%M UTC"),
    )
    return html, 200, {"Content-Type": "text/html; charset=utf-8"}
