import requests

WB_SIZES = {
    "40": "XS",
    "42": "S",
    "44": "M",
    "46": "L",
    "48": "XL",
    "50": "XXL",
    "52": "3XL",
    "54": "4XL",
    "56": "5XL"
}


def get_wb_size(size):
    size_value = size.get("techSize") or size.get("wbSize")
    if not size_value or size_value == '0':
        return

    if '-' in size_value:
        return WB_SIZES.get(size_value.split('-')[0], size_value)

    return size_value.split('/')[0]


def load_all_products(authorization: str):
    headers = {
        "Authorization": f"Bearer {authorization}"
    }

    url = "https://content-api.wildberries.ru/content/v2/get/cards/list"
    products, cursor = [], {"limit": 100}

    while True:
        response = requests.post(url, headers=headers, json={
            "settings": {
                "cursor": cursor,
                "filter": {
                    "withPhoto": -1
                }
            }
        })

        response.raise_for_status()
        data = response.json()

        products.extend(data.get("cards", []))
        if data["cursor"]["total"] < cursor["limit"]:
            break

        cursor.update({
            "updatedAt": data["cursor"]["updatedAt"],
            "nmID": data["cursor"]["nmID"]
        })

    result = []
    for product in products:
        characteristics = product.get("characteristics", [])
        colors = next((item["value"] for item in characteristics if "Цвет" in item["name"]), None)
        composition = next((item["value"] for item in characteristics if "Состав" in item["name"]), None)

        sizes = []
        barcodes = []
        barcodes_with_sizes = {}

        for size in product["sizes"]:
            wb_size = get_wb_size(size)
            if wb_size:
                sizes.append(wb_size)

            for barcode in size["skus"]:
                barcodes.append(str(barcode))
                barcodes_with_sizes[str(barcode)] = wb_size

        result.append({
            "name": product["title"],
            "article": str(product["nmID"]),
            "vendorCode": product["vendorCode"],
            "barcodes": barcodes,
            "brand": product["brand"],
            "color": ", ".join(colors) if colors else None,
            "size": ", ".join(sizes) if sizes else None,
            "composition": ", ".join(composition) if composition else None,
            "imageUrl": product["photos"][0]["c516x688"] if product.get("photos") else None,
            "barcodesWithSizes": barcodes_with_sizes
        })

    return result
