#!/usr/bin/env python3
"""
Unified URL detection for supported marketplaces.
Detects URL source and extracts product ID.
"""

import re
from typing import Optional, Tuple


def extract_url(text: str) -> Optional[str]:
    """
    Extract marketplace URL from arbitrary text.
    Handles cases where user pastes product name + URL together.

    Returns:
        The extracted URL or None if not found
    """
    # Look for WB URL
    wb_match = re.search(r'https?://[^\s]*wildberries\.ru/catalog/\d+[^\s]*', text)
    if wb_match:
        return wb_match.group(0)

    # Look for Avito URL
    avito_match = re.search(r'https?://[^\s]*avito\.ru/[^\s]+_\d+[^\s]*', text)
    if avito_match:
        return avito_match.group(0)

    # Look for Ozon URL
    ozon_match = re.search(r'https?://[^\s]*ozon\.ru/product/[^\s]+', text)
    if ozon_match:
        return ozon_match.group(0)

    return None


def detect_url_source(url: str) -> Tuple[Optional[str], Optional[str]]:
    """
    Detect marketplace source and extract product ID from URL.

    Returns:
        Tuple of (source, product_id) where source is 'wb', 'avito', 'ozon', or None
    """
    url = url.strip()

    # Wildberries: /catalog/{ID}/detail.aspx
    if 'wildberries.ru' in url:
        match = re.search(r'/catalog/(\d+)/', url)
        if match:
            return 'wb', match.group(1)

    # Avito: _ID before query string or end of URL
    if 'avito.ru/' in url:
        # Strip query string if present
        url_path = url.split('?')[0].rstrip('/')
        match = re.search(r'_(\d+)$', url_path)
        if match:
            return 'avito', match.group(1)

    # Ozon: /product/slug-ID/ or /product/ID/
    if 'ozon.ru' in url:
        url_path = url.split('?')[0].rstrip('/')
        match = re.search(r'-(\d+)$', url_path)
        if not match:
            match = re.search(r'/product/(\d+)$', url_path)
        if match:
            return 'ozon', match.group(1)

    return None, None


def is_supported_url(url: str) -> bool:
    """Check if URL is from a supported marketplace."""
    source, product_id = detect_url_source(url)
    return source is not None and product_id is not None


def get_directory_prefix(source: str) -> str:
    """Get directory prefix for marketplace."""
    return source  # 'wb', 'avito', or 'ozon'


if __name__ == "__main__":
    # Test URLs
    test_urls = [
        "https://www.wildberries.ru/catalog/271933299/detail.aspx",
        "https://www.avito.ru/ryazan/sport_i_otdyh/konki_progulochnye_bauer_2518117887",
        "https://www.ozon.ru/product/stelki-dlya-obuvi-1-sht-2153962716/",
        "https://www.ozon.ru/product/2153962716/",
        "https://example.com/product/123",
    ]

    for url in test_urls:
        source, pid = detect_url_source(url)
        print(f"{url[:50]}... -> source={source}, id={pid}")
