#!/usr/bin/env python3
"""
Simple WB Product Fetcher - No Browser Required
Uses manual data entry or JSON file input
"""

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


def find_correct_image_urls(product_id: str) -> list[str]:
    """
    Try to construct correct WB image URLs
    WB uses CDN with pattern: https://basket-XX.wbbasket.ru/volYYYY/partZZZZZZ/PRODUCT_ID/images/big/N.webp
    """
    # Calculate vol and part from product_id
    if len(product_id) < 6:
        return []

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

    # WB distributes images across 01-13 baskets
    baskets = [f"{i:02d}" for i in range(1, 14)]

    # Try different basket combinations
    all_urls = []
    for basket in baskets:
        base = f"https://basket-{basket}.wbbasket.ru/vol{vol}/part{part}/{product_id}/images/big"
        for i in range(1, 11):
            all_urls.append(f"{base}/{i}.webp")

    # Also try with .jpg extension
    for basket in baskets:
        base = f"https://basket-{basket}.wbbasket.ru/vol{vol}/part{part}/{product_id}/images/big"
        for i in range(1, 11):
            all_urls.append(f"{base}/{i}.jpg")

    return all_urls


def manual_input() -> Dict:
    """Interactive manual product data entry"""
    print("\n=== Manual Product Data Entry ===\n")
    print("Visit the WB product page and enter the information:\n")

    url = input("Product URL: ").strip()
    name = input("Product Name (from page title): ").strip()

    print("\nProduct Type (choose or type):")
    print("  1. kitchenware")
    print("  2. fashion")
    print("  3. electronics")
    print("  4. furniture")
    print("  5. beauty")
    print("  6. food")
    print("  7. other")

    type_choice = input("Enter number or type: ").strip()
    type_map = {
        "1": "kitchenware",
        "2": "fashion",
        "3": "electronics",
        "4": "furniture",
        "5": "beauty",
        "6": "food",
        "7": "other"
    }
    product_type = type_map.get(type_choice, type_choice)

    # Extract product ID
    match = re.search(r'/catalog/(\d+)/', url)
    product_id = match.group(1) if match else None

    # Try to find images
    print(f"\nTrying to locate images for product {product_id}...")
    images = find_correct_image_urls(product_id) if product_id else []

    print("\nOptional: Enter image URLs (one per line, empty line to finish):")
    manual_images = []
    while True:
        img = input().strip()
        if not img:
            break
        manual_images.append(img)

    if manual_images:
        images = manual_images

    return {
        "url": url,
        "product_id": product_id,
        "name": name,
        "type": product_type,
        "images": images[:10] if images else []
    }


def from_json_file(filepath: str) -> Optional[Dict]:
    """Load product data from JSON file"""
    try:
        with open(filepath, 'r', encoding='utf-8') as f:
            return json.load(f)
    except Exception as e:
        print(f"Error loading JSON: {e}")
        return None


def main():
    if len(sys.argv) > 1:
        if sys.argv[1] == "--manual":
            product_data = manual_input()
        elif sys.argv[1].endswith('.json'):
            product_data = from_json_file(sys.argv[1])
            if not product_data:
                sys.exit(1)
        else:
            print("Usage:")
            print("  python wb_fetcher_simple.py --manual")
            print("  python wb_fetcher_simple.py product_data.json")
            sys.exit(1)
    else:
        product_data = manual_input()

    print("\n=== Product Data ===\n")
    print(json.dumps(product_data, indent=2, ensure_ascii=False))

    # Save to file
    if product_data.get('product_id'):
        filename = f"product_{product_data['product_id']}.json"
        with open(filename, 'w', encoding='utf-8') as f:
            json.dump(product_data, f, indent=2, ensure_ascii=False)
        print(f"\nSaved to: {filename}")


if __name__ == "__main__":
    main()
