#!/usr/bin/env python3
"""
Wildberries API Fetcher
Attempts to fetch product data directly from WB API endpoints
"""

import json
import re
import requests
from typing import Dict, Optional


def fetch_wb_product_api(url: str) -> Optional[Dict]:
    """
    Fetch WB product via API endpoints

    WB has internal APIs that may be accessible:
    - Card API: card.wb.ru/cards/v2/detail
    - Basket CDN: for images
    """

    # Extract product ID
    match = re.search(r'/catalog/(\d+)/', url)
    if not match:
        print("Could not extract product ID from URL")
        return None

    product_id = match.group(1)
    print(f"Product ID: {product_id}")

    # Try WB card API
    api_url = f"https://card.wb.ru/cards/v2/detail?appType=1&curr=rub&dest=-1257786&spp=30&nm={product_id}"

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
        'Accept': 'application/json',
        'Accept-Language': 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7',
        'Referer': 'https://www.wildberries.ru/',
        'Origin': 'https://www.wildberries.ru'
    }

    try:
        print(f"Fetching from API: {api_url}")
        response = requests.get(api_url, headers=headers, timeout=10)

        if response.status_code != 200:
            print(f"API returned status {response.status_code}")
            return None

        data = response.json()

        if not data.get('data') or not data['data'].get('products'):
            print("No product data in API response")
            return None

        product = data['data']['products'][0]

        # Extract name
        name = product.get('name', '')
        brand = product.get('brand', '')

        # Extract images
        images = []
        vol = int(product_id[:4])
        part = int(product_id[:6])

        # WB image CDN pattern
        for i in range(1, 11):
            # Try different basket numbers
            for basket in range(1, 14):
                img_url = f"https://basket-{basket:02d}.wbbasket.ru/vol{vol}/part{part}/{product_id}/images/big/{i}.webp"
                images.append(img_url)

        # Get price
        price_data = product.get('salePriceU', 0) or product.get('priceU', 0)
        price = f"{price_data / 100:.2f} ₽" if price_data else ""

        # Description (if available)
        description = product.get('description', '')

        # Determine type
        name_lower = name.lower()
        product_type = 'general'

        if any(word in name_lower for word in ['сковород', 'кастрюл', 'посуд', 'тарелк']):
            product_type = 'kitchenware'
        elif any(word in name_lower for word in ['платье', 'футболк', 'брюк', 'куртк']):
            product_type = 'fashion'
        elif any(word in name_lower for word in ['наушник', 'телефон', 'ноутбук']):
            product_type = 'electronics'

        product_data = {
            'url': url,
            'product_id': product_id,
            'name': f"{brand} {name}".strip(),
            'brand': brand,
            'type': product_type,
            'price': price,
            'description': description,
            'images': images[:10],  # First 10 possible images
            'raw_data': product  # Keep raw for debugging
        }

        return product_data

    except Exception as e:
        print(f"Error fetching from API: {e}")
        return None


if __name__ == "__main__":
    import sys

    if len(sys.argv) < 2:
        print("Usage: python wb_fetcher_api.py <WB_URL>")
        sys.exit(1)

    url = sys.argv[1]
    data = fetch_wb_product_api(url)

    if data:
        print("\n=== Product Data ===")
        # Remove raw_data for clean output
        clean_data = {k: v for k, v in data.items() if k != 'raw_data'}
        print(json.dumps(clean_data, indent=2, ensure_ascii=False))

        # Save to file
        if data.get('product_id'):
            filename = f"product_{data['product_id']}.json"
            with open(filename, 'w', encoding='utf-8') as f:
                json.dump(clean_data, f, indent=2, ensure_ascii=False)
            print(f"\n✓ Saved to: {filename}")
    else:
        print("Failed to fetch product data")
