import re
from urllib.parse import parse_qs, urlparse

from django.conf import settings

from market.services.social_media import build_market_public_url


PRODUCT_PATH_RE = re.compile(
    r"^/(?:market/)?(?:catalog/products|products|product)/(?P<slug>[-\w]+)/?$",
    re.IGNORECASE,
)
LISTING_PATH_RE = re.compile(
    r"^/(?:market/)?(?:catalog/farmer-listings|farmer-listings|listing|listings)/(?P<slug>[-\w]+)/?$",
    re.IGNORECASE,
)
CATEGORY_PATH_RE = re.compile(r"^/market/catalog/categories/(?P<slug>[-\w]+)/?$", re.IGNORECASE)
ORDER_PATH_RE = re.compile(r"^/market/orders/(?P<order_id>\d+)/confirmation/?$", re.IGNORECASE)
OFFER_PATH_RE = re.compile(r"^/market/offers/(?P<offer_id>\d+)/?$", re.IGNORECASE)
NOTIFICATION_PATH_RE = re.compile(r"^/market/(?:me/)?notifications/(?P<notification_id>\d+)/?$", re.IGNORECASE)


def _normalized_app_base_url(value):
    raw_value = str(value or "").strip()
    if not raw_value:
        return ""
    if raw_value.endswith("://"):
        return raw_value
    return raw_value.rstrip("/")


def market_app_base_url():
    candidates = [
        getattr(settings, "APP_DEEP_LINK_BASE_URL", ""),
        getattr(settings, "MOBILE_APP_LINK_BASE_URL", ""),
        getattr(settings, "APP_PUBLIC_BASE_URL", ""),
        "bomabestsoko://",
    ]
    for candidate in candidates:
        normalized = _normalized_app_base_url(candidate)
        if normalized:
            return normalized
    return "bomabestsoko://"


def _action_path_and_query(path_or_url=""):
    target = str(path_or_url or "").strip()
    if not target:
        return "", {}

    if target.startswith(("http://", "https://", "bomabestsoko://")):
        parsed = urlparse(target)
        return parsed.path or "", parse_qs(parsed.query)

    if "?" in target:
        parsed = urlparse(target)
        return parsed.path or "", parse_qs(parsed.query)

    return target, {}


def market_path_to_app_path(path_or_url=""):
    path, query = _action_path_and_query(path_or_url)
    normalized_path = str(path or "").rstrip("/")

    offer_id = (query.get("offer_id") or query.get("offer") or [""])[0]
    if str(offer_id or "").strip().isdigit():
        return f"offers/{int(offer_id)}"

    notification_id = (query.get("notification_id") or [""])[0]
    if str(notification_id or "").strip().isdigit():
        return f"notifications/{int(notification_id)}"

    product_match = PRODUCT_PATH_RE.match(path)
    if product_match:
        return f"product/{product_match.group('slug')}"

    listing_match = LISTING_PATH_RE.match(path)
    if listing_match:
        return f"listing/{listing_match.group('slug')}"

    category_match = CATEGORY_PATH_RE.match(path)
    if category_match:
        return f"categories/{category_match.group('slug')}"

    order_match = ORDER_PATH_RE.match(path)
    if order_match:
        return f"orders/{int(order_match.group('order_id'))}"

    offer_match = OFFER_PATH_RE.match(path)
    if offer_match:
        return f"offers/{int(offer_match.group('offer_id'))}"

    notification_match = NOTIFICATION_PATH_RE.match(path)
    if notification_match:
        return f"notifications/{int(notification_match.group('notification_id'))}"

    if normalized_path in {
        "/market/catalog",
        "/catalog",
        "/market",
        "/market/dashboard/buyer",
        "/market/products",
        "/market/seller/products",
        "/products",
    }:
        return "market"

    if normalized_path in {
        "/market/me/notifications",
        "/market/notifications",
    }:
        return "notifications"

    if normalized_path == "/market/dashboard/field-officer":
        return "functions"

    if normalized_path == "/market/dashboard/field-officer/farmers/register":
        return "farmers/register"

    if normalized_path == "/market/dashboard/field-officer/listings/create":
        return "listings/create"

    return ""


def build_market_app_url(path_or_url="", *, fallback_path="market", include_web_fallback=False):
    app_path = market_path_to_app_path(path_or_url)
    if not app_path and fallback_path:
        app_path = str(fallback_path or "").strip().lstrip("/")

    base_url = market_app_base_url()
    if app_path:
        if base_url.endswith("://"):
            return f"{base_url}{app_path}"
        return f"{base_url}/{app_path.lstrip('/')}"

    if include_web_fallback:
        return build_market_public_url(path_or_url or "/market/catalog")
    return base_url
