import pydash
import requests

from V2.functions.BlankProducts.main import BlankProduct, BlankVariant
from V2.functions.Images.main import Image
from V2.Params import Params

api_key = "d36141d3a9504ace86ab9b5148d0c928"
au_api_key = "9a6b756f324c4d04b7ed042e158abbcf"
imageTypes = dict(
    MAIN="primary",
    FRONT="front",
    BACK="back",
)


def getAscolourProducts(pageNumber=1):
    url = f"https://api.ascolour.com/v1/catalog/products?pageNumber={pageNumber}"
    res = requests.get(url, headers={"Subscription-Key": api_key})
    return res.json().get("data")


# def getProductVariants(productId):
#     url = f"https://api.ascolour.com.au/v1/catalog/products/{productId}/variants?PageNumber=2"
#     res = requests.get(url, headers={"Subscription-Key": api_key})
#     return res.json().get("data")

def getProductVariants(productId):
    all_variants = []
    page_number = 1  # Start with the first page

    while True:
        url = f"https://api.ascolour.com/v1/catalog/products/{productId}/variants?PageNumber={page_number}"
        res = requests.get(url, headers={"Subscription-Key": api_key})
        
        # Check if the response is successful
        if res.status_code != 200:
            raise Exception(f"Failed to fetch data: {res.status_code} - {res.text}")
        
        # Get the variants from the current page
        data = [v for v in res.json().get("data") if not v.get("discontinued")]
        print(page_number, len(data))
        if not data:  # Exit loop if no more variants are available
            break
        
        all_variants.extend(data)  # Add current page's variants to the list
        page_number += 1  # Move to the next page

    return all_variants

def getProductImages(productId):
    url = f"https://api.ascolour.com/v1/catalog/products/{productId}/images"
    res = requests.get(url, headers={"Subscription-Key": api_key})
    return res.json().get("data")

def UpdateProducts(params:Params):
    products = getAscolourProducts(params.args.get("pageNumber", 1))
    # print(len(products))
    blankProductId = params.args.get("blankProductId")
    # start after "AS4006" styleCode
    # products = pydash.filter(products, lambda product: product.get("styleCode") != blankProductId)
    if blankProductId: products = [p for p in products if p.get("styleCode") == blankProductId]
    for p in products: print(p.get("styleCode"), p.get("styleName"))
    for product in products:
        images = getProductImages(product.get("styleCode"))
        blankProduct = BlankProduct(
            id=f"AS{product.get('styleCode')}",
            name=product.get("styleName"),
            description=product.get("description"),
            blankProductId=product.get("styleCode"),
            brand="Ascolour",
            public=True,
            images=[dict(url=image.get("urlZoom"), type=imageTypes.get(image.get("imageType"))) for image in images],
            primaryImage=next((image.get("urlZoom") for image in images if image.get("imageType") == "MAIN"), None),
            supplierName="Ascolour",
            supplierId="AS",
            style=product.get("styleCode"),
            categories=[],
            tags=[]
        )
        blankVariants = [
            BlankVariant(
                blankProductId=product.get("styleCode"),
                color=variant.get("colour"),
                size=variant.get("sizeCode"),
                style=product.get("styleCode"),
                weight=variant.get("weight"),
                description=variant.get("name"),
                images=get_variant_images(variant.get("colour"), images),
                id=variant.get("sku"),
                colorCode=None,
                gtin=None,
                weightUnit="grams"
            ) for variant in getProductVariants(product.get("styleCode"))
        ]
        blankProduct.save(blankVariants)
        #PRINT PERCENTAGE OF PRODUCTS SAVED
        print(f"{round((products.index(product) / len(products)) * 100, 2)}%", product.get("styleCode"))
    return products



def get_variant_images(variant_color, images):
    """
    Extracts images for a specific blank variant from an array of image objects.

    Args:
      variant_color: The color of the variant (e.g., "BLACK").
      images: An array of image objects with "imageType" and "urlZoom" attributes.

    Returns:
      An array of image dicts, each in the format {"url": image_url, "type": image_type}.
    """

    variant_images = []
    for image in images:
        image_type = image.get("imageType")
        if image_type == variant_color or image_type == f"{variant_color} - BACK":
            image_dict = {
                "url": image.get("urlZoom"),
                "type": "Rear" if image_type == f"{variant_color} - BACK" else "Front",
                "color": variant_color
            }
            variant_images.append(image_dict)
    return variant_images
