import os
import re
from flask import (
    Blueprint,
    abort,
    current_app,
    flash,
    jsonify,
    redirect,
    render_template,
    request,
    send_from_directory,
    session,
    url_for,
)
from services.cart_service import (
    add_item_to_cart,
    apply_coupon_to_cart,
    get_cart_summary,
    get_or_create_cart,
    remove_cart_item_by_product,
    remove_coupon_from_cart,
    update_cart_item_qty,
    validate_coupon,
)
from services.garage_service import (
    add_to_garage_shelf,
    create_garage_dispatch_request,
    get_customer_dispatch_requests,
    get_customer_garage_holds,
    get_customer_garage_shelf,
    move_garage_shelf_to_cart,
    update_garage_shelf_qty,
)
from services.order_service import (
    attach_payment_proof_to_order,
    create_order_from_cart,
    get_order_full_details,
    order_garage_dispatch_allowed,
    submit_customer_return_request,
)
from services.product_service import (
    attach_maker_product_counts,
    get_product_by_identifier,
    get_related_products,
    list_brands,
    list_categories,
    list_scales,
    product_to_api_dict,
    query_products,
)
from services.settings_service import (
    get_gallery_photos,
    get_homepage_sections,
    get_int_setting,
    get_model_maker_strips,
    get_store_settings,
    get_testimonials,
    get_vehicle_maker_strips,
)
from utils.db import get_db
from utils.formatting import format_inr, rupees_to_paise
from utils.security import (
    check_rate_limit,
    csrf_protect,
    customer_login_required,
    get_current_admin,
    get_current_customer,
    save_uploaded_image,
)

storefront_bp = Blueprint("storefront", __name__)


def _cart_ctx():
    cust = get_current_customer()
    cart = get_or_create_cart(cust["id"] if cust else None)
    return cust, cart


@storefront_bp.route("/")
def index():
    sections = get_homepage_sections()
    brands = list_brands(active_only=True, featured_only=True)
    catalog_res = query_products(per_page=100)
    products_list = [product_to_api_dict(p) for p in catalog_res["items"]]

    # Enrich hero slides with live product pricing & stock from DB,
    # hide sections pointing to deleted/hidden SKUs, and flag discontinued products to render muted.
    linked_sku_states = {
        (r["sku"] or "").upper(): r
        for r in get_db().execute("SELECT sku, is_visible, availability_status FROM products").fetchall()
    }

    def _linked_product_state(linked_sku: str) -> tuple[bool, bool]:
        """Return (should_display_on_home, is_discontinued)."""
        clean = (linked_sku or "").strip().upper()
        if not clean:
            return True, False
        st = linked_sku_states.get(clean)
        if not st or not st["is_visible"]:
            return False, False
        return True, (st["availability_status"] == "discontinued")

    sku_map = {p["sku"]: p for p in products_list}
    hero_slides = []
    for hs in sections.get("hero_slide", []):
        show, is_disc = _linked_product_state(hs.get("link_product_sku"))
        if not show:
            continue
        prod = sku_map.get(hs.get("link_product_sku"))
        if not prod and hs.get("link_product_sku"):
            fetched = get_product_by_identifier(hs["link_product_sku"])
            if fetched:
                prod = product_to_api_dict(fetched)
        item = dict(hs)
        item["product"] = prod
        item["is_discontinued"] = is_disc or bool(prod and prod.get("is_discontinued"))
        hero_slides.append(item)

    showcase_slides = []
    for sl in sections.get("showcase_slide", []):
        show, is_disc = _linked_product_state(sl.get("link_product_sku"))
        if not show:
            continue
        item = dict(sl)
        item["is_discontinued"] = is_disc
        showcase_slides.append(item)

    instagram_posts = []
    for post in sections.get("instagram_post", []):
        show, is_disc = _linked_product_state(post.get("link_product_sku"))
        if not show:
            continue
        item = dict(post)
        item["is_discontinued"] = is_disc
        instagram_posts.append(item)

    preorders = [p for p in products_list if p["status"] in ("pre_order", "hot_drop")]
    return render_template(
        "index.html",
        brands=brands,
        products_json=products_list,
        preorder_items=preorders,
        showcase_slides=showcase_slides,
        hero_slides=hero_slides,
        instagram_posts=instagram_posts,
        model_strips=get_model_maker_strips(),
        vehicle_strips=get_vehicle_maker_strips(),
        testimonials=get_testimonials(),
        gallery_photos=get_gallery_photos(),
    )


_POLICY_PAGES = {
    "privacy-policy": ("Privacy Policy", "policy_privacy_policy"),
    "return-refund-policy": ("Return, Refund & Cancellation Policy", "policy_return_refund_policy"),
    "terms-of-services": ("Terms & Conditions", "policy_terms_of_services"),
    "shipping-policy": ("Shipping Policy & Charges", "policy_shipping_policy"),
}


@storefront_bp.route("/about")
def about_page():
    return render_template("story.html", active_tab="about")


@storefront_bp.route("/man-behind-dwi")
def man_behind_dwi_page():
    return render_template("story.html", active_tab="founder")


@storefront_bp.route("/policies/<slug>")
def policy_page(slug: str):
    entry = _POLICY_PAGES.get(slug)
    if not entry:
        abort(404)
    title, setting_key = entry
    settings = get_store_settings()
    body_text = (settings.get(setting_key) or "").strip()
    return render_template(
        "policy.html",
        policy_slug=slug,
        policy_title=title,
        policy_body=body_text,
        all_policies=[(k, v[0]) for k, v in _POLICY_PAGES.items()],
    )


@storefront_bp.route("/models")
def all_models_page():
    items = attach_maker_product_counts("model", get_model_maker_strips())
    return render_template(
        "makers_directory.html",
        kind="model",
        page_heading="Shop by Models",
        page_subheading=f"All {len(items)} diecast scale model brands — click any brand to view available products",
        items=items,
    )


@storefront_bp.route("/vehicle-makers")
def all_vehicles_page():
    items = attach_maker_product_counts("vehicle", get_vehicle_maker_strips())
    return render_template(
        "makers_directory.html",
        kind="vehicle",
        page_heading="Shop by Vehicle Makers",
        page_subheading=f"All {len(items)} automotive marques — click any vehicle maker to view available products",
        items=items,
    )


@storefront_bp.route("/shop")
def shop():
    search = (request.args.get("q") or "").strip()
    brand = request.args.get("brand", "all")
    scale = request.args.get("scale", "all")
    category = request.args.get("category", "all")
    availability = request.args.get("availability", "all")
    pre_order_only = request.args.get("pre_order") == "1"
    sort = request.args.get("sort", "relevance" if search else "featured")
    page = request.args.get("page", 1, type=int)

    model_maker_key = (request.args.get("model_maker") or "").strip()
    vehicle_maker_key = (request.args.get("vehicle_maker") or "").strip()
    maker_kind = ""
    maker_tokens: list[str] | None = None
    active_maker_banner: dict | None = None

    if model_maker_key:
        for entry in get_model_maker_strips():
            if entry["key"] == model_maker_key or entry["name"].lower() == model_maker_key.lower():
                maker_kind = "model"
                maker_tokens = entry["tokens"]
                active_maker_banner = {"kind": "Model Brand", "name": entry["name"], "image_url": entry["image_url"]}
                break
        if not active_maker_banner:
            maker_kind = "model"
            maker_tokens = [model_maker_key.replace("_", " ").lower()]
            active_maker_banner = {"kind": "Model Brand", "name": model_maker_key.replace("_", " "), "image_url": ""}
    elif vehicle_maker_key:
        for entry in get_vehicle_maker_strips():
            if entry["key"] == vehicle_maker_key or entry["name"].lower() == vehicle_maker_key.lower():
                maker_kind = "vehicle"
                maker_tokens = entry["tokens"]
                active_maker_banner = {"kind": "Vehicle Maker", "name": entry["name"], "image_url": entry["image_url"]}
                break
        if not active_maker_banner:
            maker_kind = "vehicle"
            maker_tokens = [vehicle_maker_key.replace("_", " ").lower()]
            active_maker_banner = {"kind": "Vehicle Maker", "name": vehicle_maker_key.replace("_", " "), "image_url": ""}

    min_price_inr = request.args.get("min_price", "").strip()
    max_price_inr = request.args.get("max_price", "").strip()
    min_paise = rupees_to_paise(min_price_inr) if min_price_inr.isdigit() else None
    max_paise = rupees_to_paise(max_price_inr) if max_price_inr.isdigit() else None

    result = query_products(
        search=search,
        brand=brand,
        scale=scale,
        category=category,
        availability=availability,
        pre_order_only=pre_order_only,
        min_price_paise=min_paise,
        max_price_paise=max_paise,
        sort=sort,
        page=page,
        per_page=12,
        maker_kind=maker_kind,
        maker_tokens=maker_tokens,
    )
    return render_template(
        "shop.html",
        result=result,
        products=[product_to_api_dict(p) for p in result["items"]],
        brands=list_brands(active_only=True),
        categories=list_categories(active_only=True),
        scales=list_scales(),
        active_maker_banner=active_maker_banner,
        filters={
            "q": search,
            "brand": brand,
            "scale": scale,
            "category": category,
            "availability": availability,
            "pre_order": "1" if pre_order_only else "0",
            "min_price": min_price_inr,
            "max_price": max_price_inr,
            "sort": sort,
            "model_maker": model_maker_key,
            "vehicle_maker": vehicle_maker_key,
        },
    )


@storefront_bp.route("/product/<identifier>")
def product_detail(identifier: str):
    prod = get_product_by_identifier(identifier)
    if not prod:
        abort(404)
    cust = get_current_customer()
    in_wishlist = False
    if cust:
        row = get_db().execute(
            "SELECT 1 FROM wishlist WHERE customer_id = ? AND product_id = ?",
            (cust["id"], prod["id"]),
        ).fetchone()
        in_wishlist = row is not None
    related = get_related_products(prod, limit=4)
    return render_template(
        "product.html",
        product=prod,
        product_api=product_to_api_dict(prod),
        related=[product_to_api_dict(r) for r in related],
        in_wishlist=in_wishlist,
    )


@storefront_bp.route("/preorders")
def preorders():
    res = query_products(pre_order_only=True, sort="newest", per_page=50)
    return render_template(
        "preorders.html",
        products=[product_to_api_dict(p) for p in res["items"]],
    )


@storefront_bp.route("/cart")
def cart_page():
    cust, cart = _cart_ctx()
    summary = get_cart_summary(cart["id"], customer_id=cust["id"] if cust else None)
    return render_template("cart.html", cart_summary=summary)


@storefront_bp.route("/checkout", methods=["GET", "POST"])
@csrf_protect
def checkout_page():
    if not get_current_customer():
        flash("Please sign in or register first before checkout so you can always track your order.", "info")
        return redirect(url_for("customer.login", next=url_for("storefront.checkout_page")))

    cust, cart = _cart_ctx()
    mode = request.values.get("fulfillment_mode", "standard")
    summary = get_cart_summary(
        cart["id"],
        customer_id=cust["id"] if cust else None,
        fulfillment_mode=mode,
    )

    addresses = []
    if cust:
        addresses = [
            dict(r)
            for r in get_db().execute(
                "SELECT * FROM addresses WHERE customer_id = ? ORDER BY is_default DESC, id DESC",
                (cust["id"],),
            ).fetchall()
        ]

    if request.method == "POST":
        if not check_rate_limit("checkout_submit", 15, 300):
            flash("Too many checkout attempts. Please wait a moment.", "error")
            return render_template("checkout.html", cart_summary=summary, addresses=addresses), 429

        try:
            addr_id = request.form.get("saved_address_id")
            if addr_id and cust and addr_id != "new":
                addr_row = get_db().execute(
                    "SELECT * FROM addresses WHERE id = ? AND customer_id = ?",
                    (int(addr_id), cust["id"]),
                ).fetchone()
                if not addr_row:
                    raise ValueError("Selected address not found.")
                shipping_address = {
                    "recipient_name": addr_row["recipient_name"],
                    "phone": addr_row["phone"],
                    "address_line1": addr_row["address_line1"],
                    "address_line2": addr_row["address_line2"],
                    "city": addr_row["city"],
                    "state": addr_row["state"],
                    "pincode": addr_row["pincode"],
                }
            else:
                shipping_address = {
                    "recipient_name": (request.form.get("customer_name") or "").strip(),
                    "phone": (request.form.get("customer_phone") or "").strip(),
                    "address_line1": (request.form.get("address_line1") or "").strip(),
                    "address_line2": (request.form.get("address_line2") or "").strip(),
                    "city": (request.form.get("city") or "").strip(),
                    "state": (request.form.get("state") or "").strip(),
                    "pincode": (request.form.get("pincode") or "").strip(),
                }

            proof_info = None
            file_storage = request.files.get("payment_screenshot")
            if file_storage and file_storage.filename:
                fname, mime, size = save_uploaded_image(
                    file_storage, current_app.config["PAYMENT_PROOF_UPLOADS_DIR"], prefix="proof"
                )
                proof_info = (fname, file_storage.filename, mime, size)
            elif request.form.get("require_proof") == "1":
                raise ValueError("Please upload your UPI payment screenshot.")

            order_res = create_order_from_cart(
                cart_id=cart["id"],
                customer_id=cust["id"] if cust else None,
                customer_name=(request.form.get("customer_name") or shipping_address["recipient_name"]).strip(),
                customer_email=(request.form.get("customer_email") or (cust["email"] if cust else "")).strip(),
                customer_phone=(request.form.get("customer_phone") or shipping_address["phone"]).strip(),
                shipping_address=shipping_address,
                billing_address=None,
                fulfillment_mode=mode,
                payment_method=request.form.get("payment_method", "UPI App"),
                utr_number=(request.form.get("utr_number") or "").strip(),
                proof_file_info=proof_info,
                coupon_code=(request.form.get("coupon_code") or "").strip(),
                notes=(request.form.get("notes") or "").strip(),
            )
            allowed_orders = session.get("guest_order_numbers", [])
            allowed_orders.append(order_res["order_number"])
            session["guest_order_numbers"] = allowed_orders[-10:]
            return redirect(
                url_for(
                    "storefront.tracking_page",
                    order_number=order_res["order_number"],
                    token=order_res["tracking_token"],
                    placed="1",
                )
            )
        except ValueError as exc:
            flash(str(exc), "error")

    return render_template("checkout.html", cart_summary=summary, addresses=addresses)


@storefront_bp.route("/garage", methods=["GET", "POST"])
@customer_login_required
@csrf_protect
def garage_page():
    cust = get_current_customer()
    settings = get_store_settings()
    hold_days = get_int_setting(settings, "garage_hold_days", 60)
    dispatch_fee_paise = get_int_setting(settings, "garage_dispatch_fee_paise", 9900)
    free_dispatch_thresh = get_int_setting(settings, "garage_free_dispatch_threshold_paise", 199900)

    if request.method == "POST":
        action = request.form.get("action", "dispatch")
        try:
            if action == "checkout_shelf":
                _, cart = _cart_ctx()
                moved = move_garage_shelf_to_cart(cust["id"], cart["id"])
                flash(f"Moved {moved} model(s) from Garage Shelf to Checkout.", "success")
                return redirect(url_for("storefront.checkout_page", fulfillment_mode="garage_hold"))
            if action == "update_shelf":
                shelf_item_id = int(request.form.get("shelf_item_id"))
                qty = int(request.form.get("quantity", 0))
                update_garage_shelf_qty(cust["id"], shelf_item_id, qty)
                flash("Garage Shelf updated.", "success")
                return redirect(url_for("storefront.garage_page"))

            raw_ids = request.form.getlist("hold_ids")
            hold_ids = [int(x) for x in raw_ids if x.isdigit()]
            addr_id = request.form.get("address_id")
            if addr_id and addr_id != "new":
                addr_row = get_db().execute(
                    "SELECT * FROM addresses WHERE id = ? AND customer_id = ?",
                    (int(addr_id), cust["id"]),
                ).fetchone()
                if not addr_row:
                    raise ValueError("Selected address not found.")
                shipping_address = {
                    "recipient_name": addr_row["recipient_name"],
                    "phone": addr_row["phone"],
                    "address_line1": addr_row["address_line1"],
                    "address_line2": addr_row["address_line2"],
                    "city": addr_row["city"],
                    "state": addr_row["state"],
                    "pincode": addr_row["pincode"],
                }
            else:
                shipping_address = {
                    "recipient_name": (request.form.get("recipient_name") or cust["full_name"]).strip(),
                    "phone": (request.form.get("phone") or cust["phone"]).strip(),
                    "address_line1": (request.form.get("address_line1") or "").strip(),
                    "address_line2": (request.form.get("address_line2") or "").strip(),
                    "city": (request.form.get("city") or "").strip(),
                    "state": (request.form.get("state") or "").strip(),
                    "pincode": (request.form.get("pincode") or "").strip(),
                }
            res = create_garage_dispatch_request(
                customer_id=cust["id"],
                hold_ids=hold_ids,
                shipping_address=shipping_address,
            )
            flash(
                f"Dispatch request {res['request_number']} created for {res['item_count']} item(s)! Shipping fee: {res['shipping_fee_formatted']}",
                "success",
            )
            return redirect(url_for("storefront.garage_page"))
        except ValueError as exc:
            flash(str(exc), "error")

    shelf_items = get_customer_garage_shelf(cust["id"])
    holds = get_customer_garage_holds(cust["id"])
    dispatch_requests = get_customer_dispatch_requests(cust["id"])
    addresses = [
        dict(r)
        for r in get_db().execute(
            "SELECT * FROM addresses WHERE customer_id = ? ORDER BY is_default DESC, id DESC",
            (cust["id"],),
        ).fetchall()
    ]
    return render_template(
        "garage.html",
        shelf_items=shelf_items,
        holds=holds,
        dispatch_requests=dispatch_requests,
        addresses=addresses,
        hold_days=hold_days,
        dispatch_fee_formatted=format_inr(dispatch_fee_paise),
        free_dispatch_formatted=format_inr(free_dispatch_thresh),
    )


def _authorize_order_view(order_row, token: str, verify_contact: str) -> bool:
    if get_current_admin():
        return True
    cust = get_current_customer()
    if cust and order_row["customer_id"] == cust["id"]:
        return True
    if token and order_row["tracking_token"] == token:
        return True
    if order_row["order_number"] in session.get("guest_order_numbers", []):
        return True
    if verify_contact:
        clean_v = verify_contact.strip().lower()
        clean_digits = "".join(ch for ch in clean_v if ch.isdigit())
        if clean_digits and len(clean_digits) >= 10 and clean_digits[-10:] == order_row["customer_phone"][-10:]:
            return True
        if order_row["customer_email"] and clean_v == order_row["customer_email"].lower():
            return True
    return False


@storefront_bp.route("/tracking", methods=["GET", "POST"])
@storefront_bp.route("/tracking/<order_number>", methods=["GET", "POST"])
@csrf_protect
def tracking_page(order_number: str = ""):
    order_num_q = (order_number or request.values.get("order_number") or "").strip().upper().lstrip("#")
    token_q = (request.values.get("token") or "").strip()
    contact_q = (request.values.get("verify_contact") or "").strip()
    just_placed = request.args.get("placed") == "1"

    order_details = None
    needs_verification = False
    error_msg = ""

    if order_num_q:
        if request.method == "POST" and not check_rate_limit("tracking_lookup", 25, 300):
            error_msg = "Too many lookup attempts. Please wait a few minutes."
        else:
            row = get_db().execute(
                "SELECT * FROM orders WHERE order_number = ? COLLATE NOCASE",
                (order_num_q,),
            ).fetchone()
            if not row:
                error_msg = f"No order found matching #{order_num_q}."
            elif _authorize_order_view(row, token_q, contact_q):
                # Handle late payment proof upload or customer return request
                if request.method == "POST" and request.form.get("action") == "upload_proof":
                    try:
                        file_storage = request.files.get("payment_screenshot")
                        if not file_storage or not file_storage.filename:
                            raise ValueError("Please select a payment screenshot image.")
                        fname, mime, size = save_uploaded_image(
                            file_storage, current_app.config["PAYMENT_PROOF_UPLOADS_DIR"], prefix="proof"
                        )
                        cust = get_current_customer()
                        attach_payment_proof_to_order(
                            order_id=row["id"],
                            customer_id=cust["id"] if cust else None,
                            utr_number=(request.form.get("utr_number") or "").strip(),
                            payment_method=request.form.get("payment_method", "UPI App"),
                            proof_file_info=(fname, file_storage.filename, mime, size),
                        )
                        flash("Payment proof submitted! Status is now Payment Verification Pending.", "success")
                    except ValueError as exc:
                        flash(str(exc), "error")
                elif request.method == "POST" and request.form.get("action") == "request_return":
                    try:
                        cust = get_current_customer()
                        submit_customer_return_request(
                            order_id=row["id"],
                            customer_id=cust["id"] if cust else None,
                            actor_name=cust["full_name"] if cust else row["customer_name"],
                            reason=request.form.get("return_reason", ""),
                        )
                        flash("Return / refund request submitted. Our team will review it shortly.", "success")
                    except ValueError as exc:
                        flash(str(exc), "error")
                order_details = get_order_full_details(row["id"])
            else:
                needs_verification = True
                if request.method == "POST" and contact_q:
                    error_msg = "Phone number or email does not match this order."

    garage_dispatch_ready = (
        order_garage_dispatch_allowed(get_db(), order_details)
        if order_details
        else False
    )

    return render_template(
        "tracking.html",
        order_num=order_num_q,
        token=token_q,
        order=order_details,
        needs_verification=needs_verification,
        error_msg=error_msg,
        just_placed=just_placed,
        garage_dispatch_ready=garage_dispatch_ready,
    )


# ==========================================================================
# UPLOAD SERVING (Protected payment proofs vs public product/banner images)
# ==========================================================================
@storefront_bp.route("/uploads/products/<path:filename>")
def serve_product_upload(filename: str):
    return send_from_directory(current_app.config["PRODUCT_UPLOADS_DIR"], filename)


@storefront_bp.route("/uploads/banners/<path:filename>")
def serve_banner_upload(filename: str):
    return send_from_directory(current_app.config["BANNER_UPLOADS_DIR"], filename)


@storefront_bp.route("/uploads/payment_proofs/<path:filename>")
def serve_payment_proof(filename: str):
    """Protected route: only admin or the owning customer/session can view payment screenshots."""
    admin = get_current_admin()
    if admin:
        return send_from_directory(current_app.config["PAYMENT_PROOF_UPLOADS_DIR"], filename)

    proof = get_db().execute(
        """
        SELECT pp.*, o.customer_id, o.order_number
        FROM payment_proofs pp
        JOIN orders o ON o.id = pp.order_id
        WHERE pp.file_path = ?
        LIMIT 1
        """,
        (filename,),
    ).fetchone()
    if not proof:
        abort(404)

    cust = get_current_customer()
    if cust and proof["customer_id"] == cust["id"]:
        return send_from_directory(current_app.config["PAYMENT_PROOF_UPLOADS_DIR"], filename)

    if proof["order_number"] in session.get("guest_order_numbers", []):
        return send_from_directory(current_app.config["PAYMENT_PROOF_UPLOADS_DIR"], filename)

    abort(403)


# ==========================================================================
# STOREFRONT JSON APIs (Live Search, Cart Drawer, Checkout Modal, Wishlist)
# ==========================================================================
@storefront_bp.route("/api/products")
def api_products():
    res = query_products(
        search=request.args.get("q", ""),
        brand=request.args.get("brand", "all"),
        scale=request.args.get("scale", "all"),
        category=request.args.get("category", "all"),
        availability=request.args.get("status", "all"),
        sort=request.args.get("sort", "featured"),
        page=request.args.get("page", 1, type=int),
        per_page=request.args.get("per_page", 48, type=int),
    )
    return jsonify(
        {
            "items": [product_to_api_dict(p) for p in res["items"]],
            "total": res["total"],
            "page": res["page"],
            "pages": res["pages"],
        }
    )


@storefront_bp.route("/api/products/<identifier>")
def api_product_detail(identifier: str):
    prod = get_product_by_identifier(identifier)
    if not prod:
        return jsonify({"error": "Product not found"}), 404
    return jsonify(product_to_api_dict(prod))


@storefront_bp.route("/api/cart")
def api_get_cart():
    cust, cart = _cart_ctx()
    mode = request.args.get("fulfillment_mode", "standard")
    return jsonify(get_cart_summary(cart["id"], customer_id=cust["id"] if cust else None, fulfillment_mode=mode))


@storefront_bp.route("/api/cart/add", methods=["POST"])
@csrf_protect
def api_cart_add():
    cust, cart = _cart_ctx()
    data = request.get_json(silent=True) or {}
    ident = data.get("product_id") or data.get("sku")
    qty = int(data.get("quantity", 1))
    mode = data.get("purchase_mode", "standard")
    prod = get_product_by_identifier(str(ident))
    if not prod:
        return jsonify({"error": "Product not found"}), 404
    try:
        res = add_item_to_cart(cart["id"], prod["id"], quantity=qty, purchase_mode=mode)
        summary = get_cart_summary(cart["id"], customer_id=cust["id"] if cust else None)
        return jsonify({"ok": True, "added": res, "cart": summary})
    except ValueError as exc:
        return jsonify({"error": str(exc)}), 400


@storefront_bp.route("/api/cart/update", methods=["POST"])
@csrf_protect
def api_cart_update():
    cust, cart = _cart_ctx()
    data = request.get_json(silent=True) or {}
    item_id = data.get("cart_item_id")
    qty = int(data.get("quantity", 0))
    try:
        if item_id:
            update_cart_item_qty(cart["id"], int(item_id), qty)
        else:
            ident = data.get("product_id") or data.get("sku")
            prod = get_product_by_identifier(str(ident), include_hidden=True)
            if prod and qty <= 0:
                remove_cart_item_by_product(cart["id"], prod["id"], data.get("purchase_mode"))
        summary = get_cart_summary(cart["id"], customer_id=cust["id"] if cust else None)
        return jsonify({"ok": True, "cart": summary})
    except ValueError as exc:
        return jsonify({"error": str(exc)}), 400


@storefront_bp.route("/api/cart/coupon", methods=["POST"])
@csrf_protect
def api_cart_coupon():
    cust, cart = _cart_ctx()
    data = request.get_json(silent=True) or {}
    code = (data.get("code") or "").strip()
    try:
        if not code:
            remove_coupon_from_cart(cart["id"])
            summary = get_cart_summary(cart["id"], customer_id=cust["id"] if cust else None)
            return jsonify({"ok": True, "cart": summary})
        summary = apply_coupon_to_cart(cart["id"], code, customer_id=cust["id"] if cust else None)
        return jsonify({"ok": True, "cart": summary})
    except ValueError as exc:
        return jsonify({"error": str(exc)}), 400


@storefront_bp.route("/api/checkout", methods=["POST"])
@customer_login_required
@csrf_protect
def api_checkout():
    if not check_rate_limit("api_checkout", 15, 300):
        return jsonify({"error": "Too many checkout requests. Please wait a few minutes."}), 429

    cust, cart = _cart_ctx()
    # Accepts multipart/form-data (for payment screenshot upload)
    customer_name = (request.form.get("name") or "").strip()
    customer_phone = (request.form.get("phone") or "").strip()
    customer_email = (request.form.get("email") or (cust["email"] if cust else "")).strip()
    address = (request.form.get("address") or "").strip()
    city = (request.form.get("city") or "").strip()
    pincode = (request.form.get("pincode") or "").strip()
    mode = request.form.get("deliveryMode", "standard")
    if mode == "hold":
        mode = "garage_hold"
    payment_method = request.form.get("paymentMethod", "UPI App")
    utr_number = (request.form.get("utrNumber") or "").strip()
    coupon_code = (request.form.get("couponCode") or "").strip()

    try:
        file_storage = request.files.get("screenshot")
        if not file_storage or not file_storage.filename:
            raise ValueError("Payment screenshot is mandatory to place your order.")
        fname, mime, size = save_uploaded_image(
            file_storage, current_app.config["PAYMENT_PROOF_UPLOADS_DIR"], prefix="proof"
        )
        res = create_order_from_cart(
            cart_id=cart["id"],
            customer_id=cust["id"] if cust else None,
            customer_name=customer_name,
            customer_email=customer_email,
            customer_phone=customer_phone,
            shipping_address={
                "recipient_name": customer_name,
                "phone": customer_phone,
                "address_line1": address,
                "address_line2": "",
                "city": city,
                "state": "",
                "pincode": pincode,
            },
            billing_address=None,
            fulfillment_mode=mode,
            payment_method=payment_method,
            utr_number=utr_number,
            proof_file_info=(fname, file_storage.filename, mime, size),
            coupon_code=coupon_code,
        )
        allowed_orders = session.get("guest_order_numbers", [])
        allowed_orders.append(res["order_number"])
        session["guest_order_numbers"] = allowed_orders[-10:]
        return jsonify({"ok": True, "order": res})
    except ValueError as exc:
        return jsonify({"error": str(exc)}), 400


@storefront_bp.route("/api/garage")
def api_garage():
    cust = get_current_customer()
    if not cust:
        return jsonify(
            {
                "authenticated": False,
                "shelf": [],
                "shelf_count": 0,
                "shelf_total_paise": 0,
                "shelf_total_formatted": "₹0",
                "holds": [],
                "dispatch_requests": [],
            }
        )
    shelf = get_customer_garage_shelf(cust["id"])
    shelf_count = sum(int(i["quantity"]) for i in shelf)
    shelf_total_paise = sum(int(i["line_total_paise"]) for i in shelf)
    holds = get_customer_garage_holds(cust["id"])
    reqs = get_customer_dispatch_requests(cust["id"])
    return jsonify(
        {
            "authenticated": True,
            "shelf": shelf,
            "shelf_count": shelf_count,
            "shelf_total_paise": shelf_total_paise,
            "shelf_total_formatted": format_inr(shelf_total_paise),
            "holds": holds,
            "dispatch_requests": reqs,
        }
    )


@storefront_bp.route("/api/garage/shelf/add", methods=["POST"])
@csrf_protect
def api_garage_shelf_add():
    cust = get_current_customer()
    if not cust:
        return jsonify({"error": "Please sign in to hold models in your Collector Garage.", "login_required": True}), 401
    data = request.get_json(silent=True) or {}
    ident = data.get("product_id") or data.get("sku")
    qty = int(data.get("quantity", 1))
    prod = get_product_by_identifier(str(ident))
    if not prod:
        return jsonify({"error": "Product not found"}), 404
    try:
        added = add_to_garage_shelf(cust["id"], prod["id"], quantity=qty)
        return jsonify({"ok": True, "added": added})
    except ValueError as exc:
        return jsonify({"error": str(exc)}), 400


@storefront_bp.route("/api/garage/shelf/update", methods=["POST"])
@csrf_protect
def api_garage_shelf_update():
    cust = get_current_customer()
    if not cust:
        return jsonify({"error": "Authentication required", "login_required": True}), 401
    data = request.get_json(silent=True) or {}
    shelf_item_id = int(data.get("shelf_item_id", 0))
    qty = int(data.get("quantity", 0))
    try:
        update_garage_shelf_qty(cust["id"], shelf_item_id, qty)
        return jsonify({"ok": True})
    except ValueError as exc:
        return jsonify({"error": str(exc)}), 400


@storefront_bp.route("/api/garage/shelf/checkout", methods=["POST"])
@csrf_protect
def api_garage_shelf_checkout():
    cust = get_current_customer()
    if not cust:
        return jsonify({"error": "Authentication required", "login_required": True}), 401
    _, cart = _cart_ctx()
    try:
        moved = move_garage_shelf_to_cart(cust["id"], cart["id"])
        summary = get_cart_summary(cart["id"], customer_id=cust["id"], fulfillment_mode="garage_hold")
        return jsonify({"ok": True, "moved": moved, "cart": summary})
    except ValueError as exc:
        return jsonify({"error": str(exc)}), 400


@storefront_bp.route("/api/wishlist/toggle", methods=["POST"])
@csrf_protect
def api_wishlist_toggle():
    cust = get_current_customer()
    if not cust:
        return jsonify({"error": "Please sign in to save items to your wishlist.", "login_required": True}), 401
    data = request.get_json(silent=True) or {}
    ident = data.get("product_id") or data.get("sku")
    prod = get_product_by_identifier(str(ident))
    if not prod:
        return jsonify({"error": "Product not found"}), 404
    db = get_db()
    exists = db.execute(
        "SELECT id FROM wishlist WHERE customer_id = ? AND product_id = ?",
        (cust["id"], prod["id"]),
    ).fetchone()
    if exists:
        db.execute("DELETE FROM wishlist WHERE id = ?", (exists["id"],))
        db.commit()
        return jsonify({"ok": True, "in_wishlist": False})
    db.execute(
        "INSERT INTO wishlist (customer_id, product_id) VALUES (?, ?)",
        (cust["id"], prod["id"]),
    )
    db.commit()
    return jsonify({"ok": True, "in_wishlist": True})


_DROP_EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")


@storefront_bp.route("/api/drop-alerts/subscribe", methods=["POST"])
@csrf_protect
def api_drop_alerts_subscribe():
    data = request.get_json(silent=True) or {}
    raw_email = (data.get("email") or request.form.get("email") or "").strip().lower()
    if not raw_email or len(raw_email) > 254 or not _DROP_EMAIL_RE.match(raw_email):
        if request.is_json:
            return jsonify({"error": "Please enter a valid email address."}), 400
        flash("Please enter a valid email address.", "error")
        return redirect(url_for("storefront.index") + "#dropAlertsSection")

    db = get_db()
    existing = db.execute(
        "SELECT id, is_active FROM drop_alert_subscribers WHERE email = ? COLLATE NOCASE",
        (raw_email,),
    ).fetchone()
    if existing:
        if existing["is_active"]:
            msg = "You're already subscribed to Drop Alerts!"
        else:
            db.execute(
                "UPDATE drop_alert_subscribers SET is_active = 1, updated_at = datetime('now') WHERE id = ?",
                (existing["id"],),
            )
            db.commit()
            msg = "Welcome back! Drop Alerts re-enabled for your email."
    else:
        db.execute(
            "INSERT INTO drop_alert_subscribers (email, source, is_active) VALUES (?, 'homepage', 1)",
            (raw_email,),
        )
        db.commit()
        msg = "You're on the list! We'll email you when a new drop lands."

    if request.is_json:
        return jsonify({"ok": True, "email": raw_email, "message": msg})
    flash(msg, "success")
    return redirect(url_for("storefront.index") + "#dropAlertsSection")


@storefront_bp.route("/api/drop-alerts/unsubscribe", methods=["POST"])
@csrf_protect
def api_drop_alerts_unsubscribe():
    data = request.get_json(silent=True) or {}
    raw_email = (data.get("email") or request.form.get("email") or "").strip().lower()
    if not raw_email or not _DROP_EMAIL_RE.match(raw_email):
        return jsonify({"error": "Please enter a valid email address."}), 400
    db = get_db()
    cur = db.execute(
        "UPDATE drop_alert_subscribers SET is_active = 0, updated_at = datetime('now') WHERE email = ? COLLATE NOCASE",
        (raw_email,),
    )
    db.commit()
    if cur.rowcount == 0:
        return jsonify({"ok": True, "message": "This email is not currently subscribed."})
    return jsonify({"ok": True, "message": "Unsubscribed successfully. You will no longer receive drop alert emails."})
