import requests
from django.core.management.base import BaseCommand
from core.models import Product, Variation
from django.conf import settings
from decimal import Decimal

class Command(BaseCommand):
    help = "Sync products and variations from WooCommerce REST API"

    CK = "ck_e4107000984fd8752473cdd7974e41d227705215"
    CS = "cs_c200854aaf7a9798feae9c0844219a36cb5e46bd"
    BASE_URL = "https://theothers.com.ua/wp-json/wc/v3/"

    def handle(self, *args, **options):
        self.stdout.write("Starting sync from WooCommerce...")
        
        # 1. Fetch Products
        page = 1
        while True:
            response = requests.get(
                f"{self.BASE_URL}products",
                auth=(self.CK, self.CS),
                params={"page": page, "per_page": 100}
            )
            
            if response.status_code != 200:
                self.stderr.write(f"Error fetching products: {response.text}")
                break
                
            products_data = response.json()
            if not products_data:
                break
                
            for p in products_data:
                # Map product fields
                wp_id = str(p.get("id"))
                name = p.get("name")
                sku = p.get("sku")
                price = Decimal(p.get("price") or 0)
                stock_status = p.get("stock_status", "outofstock")
                total_sales = p.get("total_sales", 0)
                image_url = p.get("images")[0]["src"] if p.get("images") else None
                
                product, created = Product.objects.update_or_create(
                    wp_id=wp_id,
                    defaults={
                        "name": name,
                        "sku": sku,
                        "price": price,
                        "stock_status": stock_status,
                        "total_sales": total_sales,
                        "image": image_url,
                    }
                )
                
                # 2. Fetch Variations for variable products
                if p.get("type") == "variable":
                    v_response = requests.get(
                        f"{self.BASE_URL}products/{wp_id}/variations",
                        auth=(self.CK, self.CS),
                        params={"per_page": 100}
                    )
                    
                    if v_response.status_code == 200:
                        variations_data = v_response.json()
                        # Clear old variations to keep it clean (optional, but safer for simple sync)
                        # Variation.objects.filter(product=product).delete()
                        
                        for v in variations_data:
                            # Use attributes to find size
                            attributes = v.get("attributes", [])
                            size = "Default"
                            for attr in attributes:
                                if attr.get("name").lower() in ["size", "розмір"]:
                                    size = attr.get("option")
                                    break
                            
                            v_price = Decimal(v.get("price") or 0)
                            v_stock = v.get("stock_quantity") or 0
                            
                            Variation.objects.update_or_create(
                                product=product,
                                size=size,
                                defaults={
                                    "price": v_price,
                                    "stock_quantity": v_stock,
                                }
                            )

            self.stdout.write(f"Processed page {page}")
            page += 1
            
        self.stdout.write(self.style.SUCCESS("Successfully synced WooCommerce data!"))
