import json
import re
from typing import Any
from utils.db import get_db, transaction
from utils.formatting import (
    extract_model_code,
    format_inr,
    parse_json_safe,
    slugify,
    strip_model_codes_for_card,
)


def _matches_word_token(text: str, token: str) -> bool:
    clean = str(token or "").strip().lower()
    if not clean:
        return False
    pattern = r"(?:^|[^a-z0-9])" + re.escape(clean) + r"(?:$|[^a-z0-9])"
    return bool(re.search(pattern, str(text or ""), flags=re.IGNORECASE))


def attach_maker_product_counts(kind: str, strips: list[dict]) -> list[dict]:
    """Attach accurate `product_count` for each Model Brand or Vehicle Maker strip card."""
    rows = get_db().execute(
        """
        SELECT p.name, p.vehicle_model, p.manufacturer, p.tags, b.name AS brand_name
        FROM products p
        JOIN brands b ON b.id = p.brand_id
        WHERE p.is_visible = 1
        """
    ).fetchall()

    haystacks = []
    for r in rows:
        if kind == "model":
            haystacks.append(f"{r['brand_name'] or ''} {r['manufacturer'] or ''} {r['tags'] or ''}")
        else:
            haystacks.append(f"{r['vehicle_model'] or ''} {r['name'] or ''} {r['tags'] or ''}")

    enriched = []
    for item in strips:
        copy_item = dict(item)
        tokens = [t.strip().lower() for t in copy_item.get("tokens", []) if t and t.strip()]
        cnt = 0
        for hay in haystacks:
            if any(_matches_word_token(hay, tok) for tok in tokens):
                cnt += 1
        copy_item["product_count"] = cnt
        enriched.append(copy_item)
    return enriched


def _hydrate_product(row) -> dict[str, Any]:
    d = dict(row)
    specs = parse_json_safe(d.get("specifications_json"), {})
    d["specs"] = specs
    stock_qty = int(d.get("stock_qty") or 0)
    reserved_qty = int(d.get("reserved_qty") or 0)
    available_qty = max(0, stock_qty - reserved_qty)
    d["stock_qty"] = stock_qty
    d["reserved_qty"] = reserved_qty
    d["available_qty"] = available_qty
    d["low_stock_threshold"] = int(d.get("low_stock_threshold") or 3)

    if d.get("is_pre_order"):
        alloc = int(d.get("pre_order_allocation") or 0)
        res_po = int(d.get("pre_order_reserved_count") or 0)
        d["pre_order_remaining"] = max(0, alloc - res_po) if alloc > 0 else available_qty
        token = int(d.get("pre_order_token_paise") or 0)
        d["pre_order_balance_paise"] = max(0, int(d["price_paise"]) - token)
    else:
        d["pre_order_remaining"] = available_qty
        d["pre_order_balance_paise"] = 0

    d["price_formatted"] = format_inr(d["price_paise"])
    d["mrp_formatted"] = format_inr(d["mrp_paise"])
    d["savings_paise"] = max(0, int(d["mrp_paise"]) - int(d["price_paise"]))
    d["savings_formatted"] = format_inr(d["savings_paise"])
    d["token_formatted"] = format_inr(d.get("pre_order_token_paise") or 0)
    d["balance_formatted"] = format_inr(d["pre_order_balance_paise"])
    d["is_discontinued"] = bool(d.get("availability_status") == "discontinued")
    d["card_title"] = strip_model_codes_for_card(d.get("name")) or d.get("name", "")
    d["model_code"] = extract_model_code(f"{d.get('name', '')} {d.get('vehicle_model', '')}")
    d["effectively_sold_out"] = bool(
        d["is_discontinued"]
        or d.get("is_sold_out")
        or d.get("availability_status") == "sold_out"
        or (not d.get("is_pre_order") and available_qty <= 0)
        or (d.get("is_pre_order") and d["pre_order_remaining"] <= 0)
    )
    return d


def list_brands(active_only: bool = True, featured_only: bool = False) -> list[dict]:
    clauses = []
    if active_only:
        clauses.append("is_active = 1")
    if featured_only:
        clauses.append("is_featured = 1")
    where = ("WHERE " + " AND ".join(clauses)) if clauses else ""
    rows = get_db().execute(
        f"SELECT * FROM brands {where} ORDER BY sort_order ASC, name ASC"
    ).fetchall()
    return [dict(r) for r in rows]


def list_categories(active_only: bool = True) -> list[dict]:
    where = "WHERE is_active = 1" if active_only else ""
    rows = get_db().execute(
        f"SELECT * FROM categories {where} ORDER BY sort_order ASC, name ASC"
    ).fetchall()
    return [dict(r) for r in rows]


def list_scales() -> list[str]:
    rows = get_db().execute(
        "SELECT DISTINCT scale FROM products WHERE is_visible = 1 ORDER BY scale ASC"
    ).fetchall()
    return [r["scale"] for r in rows if r["scale"]]


def get_product_images(product_id: int) -> list[dict]:
    rows = get_db().execute(
        """
        SELECT id, product_id, image_url, is_primary, sort_order, alt_text
        FROM product_images
        WHERE product_id = ?
        ORDER BY is_primary DESC, sort_order ASC, id ASC
        """,
        (product_id,),
    ).fetchall()
    return [dict(r) for r in rows]


def _attach_product_images(items: list[dict]) -> list[dict]:
    """Batch-attach full `images` and deduplicated `image_urls` onto product dicts."""
    if not items:
        return items
    ids = [int(it["id"]) for it in items if it.get("id") is not None]
    if not ids:
        return items
    placeholders = ",".join("?" for _ in ids)
    rows = get_db().execute(
        f"""
        SELECT id, product_id, image_url, is_primary, sort_order, alt_text
        FROM product_images
        WHERE product_id IN ({placeholders})
        ORDER BY product_id ASC, is_primary DESC, sort_order ASC, id ASC
        """,
        ids,
    ).fetchall()
    grouped: dict[int, list[dict]] = {}
    for r in rows:
        d = dict(r)
        grouped.setdefault(int(d["product_id"]), []).append(d)
    for it in items:
        pid = int(it["id"])
        imgs = grouped.get(pid, [])
        it["images"] = imgs
        urls: list[str] = []
        primary = it.get("primary_image") or "/static/assets/images/logo.png"
        if primary:
            urls.append(primary)
        for im in imgs:
            u = im.get("image_url")
            if u and u not in urls:
                urls.append(u)
        it["image_urls"] = urls or [primary]
    return items


def get_product_by_identifier(identifier: str, include_hidden: bool = False) -> dict | None:
    vis_clause = "" if include_hidden else "AND p.is_visible = 1"
    where_col = "p.id = ?" if str(identifier).isdigit() else "(p.sku = ? COLLATE NOCASE OR p.slug = ?)"
    params = (int(identifier),) if str(identifier).isdigit() else (identifier, identifier)
    row = get_db().execute(
        f"""
        SELECT p.*, b.name AS brand_name, b.slug AS brand_slug,
               c.name AS category_name, c.slug AS category_slug,
               COALESCE(i.stock_qty, 0) AS stock_qty,
               COALESCE(i.reserved_qty, 0) AS reserved_qty,
               COALESCE(i.low_stock_threshold, 3) AS low_stock_threshold,
               COALESCE(
                   (SELECT image_url FROM product_images pi WHERE pi.product_id = p.id ORDER BY pi.is_primary DESC, pi.sort_order ASC, pi.id ASC LIMIT 1),
                   '/static/assets/images/logo.png'
               ) AS primary_image
        FROM products p
        JOIN brands b ON b.id = p.brand_id
        JOIN categories c ON c.id = p.category_id
        LEFT JOIN inventory i ON i.product_id = p.id
        WHERE {where_col} {vis_clause}
        LIMIT 1
        """,
        params,
    ).fetchone()
    if not row:
        return None
    prod = _hydrate_product(row)
    prod["images"] = get_product_images(prod["id"])
    prod["image_urls"] = [im["image_url"] for im in prod["images"] if im.get("image_url")] or [prod["primary_image"]]
    return prod


def query_products(
    *,
    search: str = "",
    brand: str = "all",
    scale: str = "all",
    category: str = "all",
    availability: str = "all",
    pre_order_only: bool = False,
    min_price_paise: int | None = None,
    max_price_paise: int | None = None,
    sort: str = "featured",
    page: int = 1,
    per_page: int = 24,
    include_hidden: bool = False,
    maker_kind: str = "",
    maker_tokens: list[str] | None = None,
) -> dict[str, Any]:
    clauses = []
    params: list[Any] = []

    if not include_hidden:
        clauses.append("p.is_visible = 1")

    if brand and brand.lower() != "all":
        clauses.append("(b.name = ? COLLATE NOCASE OR b.slug = ? COLLATE NOCASE)")
        params.extend([brand, brand])

    if scale and scale.lower() != "all":
        clauses.append("p.scale = ? COLLATE NOCASE")
        params.append(scale)

    if category and category.lower() != "all":
        clauses.append("(c.name = ? COLLATE NOCASE OR c.slug = ? COLLATE NOCASE)")
        params.extend([category, category])

    if pre_order_only:
        clauses.append("p.is_pre_order = 1")

    if availability and availability.lower() != "all":
        av = availability.lower()
        if av == "in_stock":
            clauses.append("p.availability_status IN ('in_stock', 'hot_drop') AND p.is_sold_out = 0 AND (COALESCE(i.stock_qty, 0) - COALESCE(i.reserved_qty, 0)) > 0")
        elif av == "pre_order":
            clauses.append("(p.availability_status = 'pre_order' OR p.is_pre_order = 1)")
        elif av == "hot_drop":
            clauses.append("(p.availability_status = 'hot_drop' OR p.is_limited_edition = 1)")
        elif av == "sold_out":
            clauses.append("(p.availability_status = 'sold_out' OR p.is_sold_out = 1 OR (p.is_pre_order = 0 AND (COALESCE(i.stock_qty, 0) - COALESCE(i.reserved_qty, 0)) <= 0))")
        else:
            clauses.append("p.availability_status = ?")
            params.append(av)

    if min_price_paise is not None and min_price_paise > 0:
        clauses.append("p.price_paise >= ?")
        params.append(min_price_paise)

    if max_price_paise is not None and max_price_paise > 0:
        clauses.append("p.price_paise <= ?")
        params.append(max_price_paise)

    q = (search or "").strip()
    if q:
        like = f"%{q}%"
        clauses.append(
            """(
                p.name LIKE ? COLLATE NOCASE
                OR p.sku LIKE ? COLLATE NOCASE
                OR p.vehicle_model LIKE ? COLLATE NOCASE
                OR p.manufacturer LIKE ? COLLATE NOCASE
                OR b.name LIKE ? COLLATE NOCASE
                OR p.scale LIKE ? COLLATE NOCASE
                OR p.tags LIKE ? COLLATE NOCASE
                OR p.description LIKE ? COLLATE NOCASE
            )"""
        )
        params.extend([like] * 8)

    where_sql = ("WHERE " + " AND ".join(clauses)) if clauses else ""

    order_map = {
        "featured": (
            "CASE "
            "WHEN p.availability_status IN ('in_stock', 'hot_drop') AND p.is_pre_order = 0 "
            "AND p.is_sold_out = 0 AND (COALESCE(i.stock_qty, 0) - COALESCE(i.reserved_qty, 0)) > 0 THEN 0 "
            "WHEN p.is_pre_order = 1 AND p.availability_status != 'discontinued' AND p.is_sold_out = 0 THEN 1 "
            "ELSE 2 END ASC, p.is_featured DESC, p.id ASC"
        ),
        "newest": "p.created_at DESC, p.id DESC",
        "price-low": "p.price_paise ASC, p.id ASC",
        "price-high": "p.price_paise DESC, p.id ASC",
        "title": "p.name ASC",
        "relevance": (
            "CASE WHEN p.sku LIKE ? COLLATE NOCASE THEN 0 "
            "WHEN p.name LIKE ? COLLATE NOCASE THEN 1 "
            "WHEN p.vehicle_model LIKE ? COLLATE NOCASE THEN 2 "
            "ELSE 3 END, p.is_featured DESC, p.id ASC"
        ),
    }
    order_sql = order_map.get(sort, order_map["featured"])
    order_params: list[Any] = []
    if sort == "relevance" and q:
        like_start = f"{q}%"
        order_params = [like_start, f"%{q}%", f"%{q}%"]
    elif sort == "relevance":
        order_sql = order_map["featured"]

    db = get_db()
    page = max(1, int(page))
    per_page = max(1, min(100, int(per_page)))
    offset = (page - 1) * per_page

    base_select = f"""
        SELECT p.*, b.name AS brand_name, b.slug AS brand_slug,
               c.name AS category_name, c.slug AS category_slug,
               COALESCE(i.stock_qty, 0) AS stock_qty,
               COALESCE(i.reserved_qty, 0) AS reserved_qty,
               COALESCE(i.low_stock_threshold, 3) AS low_stock_threshold,
               COALESCE(
                   (SELECT image_url FROM product_images pi WHERE pi.product_id = p.id ORDER BY pi.is_primary DESC, pi.sort_order ASC, pi.id ASC LIMIT 1),
                   '/static/assets/images/logo.png'
               ) AS primary_image
        FROM products p
        JOIN brands b ON b.id = p.brand_id
        JOIN categories c ON c.id = p.category_id
        LEFT JOIN inventory i ON i.product_id = p.id
        {where_sql}
        ORDER BY {order_sql}
    """

    tokens = [t.strip().lower() for t in (maker_tokens or []) if t and t.strip()]
    if maker_kind in ("model", "vehicle") and tokens:
        all_rows = db.execute(base_select, [*params, *order_params]).fetchall()
        matched_items: list[dict[str, Any]] = []
        for r in all_rows:
            item = _hydrate_product(r)
            if maker_kind == "model":
                hay = f"{item.get('brand_name', '')} {item.get('manufacturer', '')} {item.get('tags', '')}"
            else:
                hay = f"{item.get('vehicle_model', '')} {item.get('name', '')} {item.get('tags', '')}"
            if any(_matches_word_token(hay, tok) for tok in tokens):
                matched_items.append(item)
        total = len(matched_items)
        items = matched_items[offset : offset + per_page]
    else:
        total_row = db.execute(
            f"""
            SELECT COUNT(*) AS cnt
            FROM products p
            JOIN brands b ON b.id = p.brand_id
            JOIN categories c ON c.id = p.category_id
            LEFT JOIN inventory i ON i.product_id = p.id
            {where_sql}
            """,
            params,
        ).fetchone()
        total = int(total_row["cnt"]) if total_row else 0
        rows = db.execute(
            f"{base_select} LIMIT ? OFFSET ?",
            [*params, *order_params, per_page, offset],
        ).fetchall()
        items = [_hydrate_product(r) for r in rows]

    pages = max(1, (total + per_page - 1) // per_page)
    _attach_product_images(items)
    return {
        "items": items,
        "total": total,
        "page": page,
        "per_page": per_page,
        "pages": pages,
    }


def get_related_products(product: dict, limit: int = 4) -> list[dict]:
    rows = get_db().execute(
        """
        SELECT p.*, b.name AS brand_name, b.slug AS brand_slug,
               c.name AS category_name, c.slug AS category_slug,
               COALESCE(i.stock_qty, 0) AS stock_qty,
               COALESCE(i.reserved_qty, 0) AS reserved_qty,
               COALESCE(i.low_stock_threshold, 3) AS low_stock_threshold,
               COALESCE(
                   (SELECT image_url FROM product_images pi WHERE pi.product_id = p.id ORDER BY pi.is_primary DESC, pi.sort_order ASC, pi.id ASC LIMIT 1),
                   '/static/assets/images/logo.png'
               ) AS primary_image
        FROM products p
        JOIN brands b ON b.id = p.brand_id
        JOIN categories c ON c.id = p.category_id
        LEFT JOIN inventory i ON i.product_id = p.id
        WHERE p.is_visible = 1 AND p.id != ? AND (p.brand_id = ? OR p.scale = ?)
        ORDER BY CASE WHEN p.brand_id = ? THEN 0 ELSE 1 END, p.is_featured DESC, p.id ASC
        LIMIT ?
        """,
        (product["id"], product["brand_id"], product["scale"], product["brand_id"], limit),
    ).fetchall()
    return _attach_product_images([_hydrate_product(r) for r in rows])


def adjust_inventory(
    product_id: int,
    new_stock_qty: int,
    note: str,
    actor_type: str = "admin",
    actor_id: int | None = None,
    low_stock_threshold: int | None = None,
) -> dict:
    if new_stock_qty < 0:
        raise ValueError("Stock quantity cannot be negative.")
    with transaction() as conn:
        inv = conn.execute(
            "SELECT stock_qty, reserved_qty, low_stock_threshold FROM inventory WHERE product_id = ?",
            (product_id,),
        ).fetchone()
        if not inv:
            raise ValueError("Inventory record not found.")
        if new_stock_qty < int(inv["reserved_qty"]):
            raise ValueError(
                f"Cannot set stock below currently reserved units ({inv['reserved_qty']})."
            )
        prev = int(inv["stock_qty"])
        delta = new_stock_qty - prev
        thresh = low_stock_threshold if low_stock_threshold is not None else int(inv["low_stock_threshold"])
        conn.execute(
            """
            UPDATE inventory
            SET stock_qty = ?, low_stock_threshold = ?, updated_at = datetime('now')
            WHERE product_id = ?
            """,
            (new_stock_qty, thresh, product_id),
        )
        if delta != 0:
            conn.execute(
                """
                INSERT INTO inventory_history (
                    product_id, change_qty, previous_qty, new_qty, change_type, note, actor_type, actor_id
                ) VALUES (?, ?, ?, ?, 'adjustment', ?, ?, ?)
                """,
                (product_id, delta, prev, new_stock_qty, note, actor_type, actor_id),
            )
        # Keep sold_out flag synced if stock becomes 0 for non-preorder
        prod = conn.execute("SELECT is_pre_order, availability_status FROM products WHERE id = ?", (product_id,)).fetchone()
        if prod and not prod["is_pre_order"]:
            if new_stock_qty - int(inv["reserved_qty"]) <= 0:
                conn.execute(
                    "UPDATE products SET is_sold_out = 1, availability_status = 'sold_out', updated_at = datetime('now') WHERE id = ?",
                    (product_id,),
                )
            elif prod["availability_status"] == "sold_out":
                conn.execute(
                    "UPDATE products SET is_sold_out = 0, availability_status = 'in_stock', updated_at = datetime('now') WHERE id = ?",
                    (product_id,),
                )
        return {"previous": prev, "new": new_stock_qty, "delta": delta}


def product_to_api_dict(p: dict) -> dict:
    """Serialize product for storefront JSON APIs."""
    return {
        "id": p["id"],
        "sku": p["sku"],
        "slug": p["slug"],
        "title": p["name"],
        "card_title": p.get("card_title") or p["name"],
        "model_code": p.get("model_code") or "",
        "name": p["name"],
        "brand": p["brand_name"],
        "category": p["category_name"],
        "category_slug": p.get("category_slug", ""),
        "manufacturer": p["manufacturer"],
        "vehicle_model": p["vehicle_model"],
        "scale": p["scale"],
        "price": p["price_paise"] // 100,
        "price_paise": p["price_paise"],
        "price_formatted": p["price_formatted"],
        "originalPrice": p["mrp_paise"] // 100,
        "mrp_paise": p["mrp_paise"],
        "mrp_formatted": p["mrp_formatted"],
        "discount_percent": p["discount_percent"],
        "status": p["availability_status"],
        "badge": p["badge_text"],
        "badgeType": p["badge_type"],
        "chassis": p["specs"].get("chassis", "Diecast Metal"),
        "wheels": p["specs"].get("wheels", "Real Rider Rubber"),
        "opening": p["specs"].get("opening", "Precision Sealed"),
        "packaging": p["specs"].get("packaging", "Mint Box"),
        "specs": p["specs"],
        "condition": p["condition"],
        "tags": p.get("tags", ""),
        "image": p["primary_image"],
        "images": p.get("images", []),
        "image_urls": p.get("image_urls") or [p["primary_image"]],
        "description": p["description"],
        "stockQty": p["available_qty"],
        "stock_qty": p["stock_qty"],
        "reserved_qty": p["reserved_qty"],
        "available_qty": p["available_qty"],
        "is_featured": bool(p["is_featured"]),
        "is_limited_edition": bool(p["is_limited_edition"]),
        "is_discontinued": bool(p.get("is_discontinued") or p.get("availability_status") == "discontinued"),
        "is_sold_out": p["effectively_sold_out"],
        "is_pre_order": bool(p["is_pre_order"]),
        "garage_hold_eligible": bool(p["garage_hold_eligible"]),
        "deposit": p["pre_order_token_paise"] // 100,
        "pre_order_token_paise": p["pre_order_token_paise"],
        "pre_order_balance_paise": p["pre_order_balance_paise"],
        "token_formatted": p["token_formatted"],
        "balance_formatted": p["balance_formatted"],
        "preOrderETA": p["expected_arrival_date"],
        "expected_release_date": p["expected_release_date"],
        "expected_arrival_date": p["expected_arrival_date"],
        "pre_order_remaining": p["pre_order_remaining"],
        "pre_order_limit": p["pre_order_limit_per_customer"],
    }
