import requests
import csv

ACCESS_TOKEN_SANDBOX = "EAAAl2nmymzDWX99pGwmqWMFpWiKYvDhHa1aSY_UfjfOFuTXtJ37MfdIeXnkM4_X"
ACCESS_TOKEN = "EAAAlzTxcLpe46hddBlJOn5W7kw7AhlOS75IQoVrilB1LbXfO5qH0RlKZj4ceXQN"

BASE_URL = "https://connect.squareup.com/v2"
HEADERS = {
    "Authorization": f"Bearer {ACCESS_TOKEN}",
    "Content-Type": "application/json"
}

# ---------- FETCH ITEMS (catalog/list is fine for this) ----------
def fetch_catalog_items():
    objects = []
    cursor = None

    while True:
        params = {}
        if cursor:
            params["cursor"] = cursor

        r = requests.get(
            f"{BASE_URL}/catalog/list",
            headers=HEADERS,
            params=params
        )
        r.raise_for_status()
        data = r.json()

        objects.extend(data.get("objects", []))
        cursor = data.get("cursor")
        if not cursor:
            break

    return objects

# ---------- FETCH IMAGES (MUST use catalog/search) ----------
def fetch_catalog_images():
    images = {}
    cursor = None

    while True:
        payload = {
            "object_types": ["IMAGE"]
        }
        if cursor:
            payload["cursor"] = cursor

        r = requests.post(
            f"{BASE_URL}/catalog/search",
            headers=HEADERS,
            json=payload
        )
        r.raise_for_status()
        data = r.json()

        for obj in data.get("objects", []):
            images[obj["id"]] = obj

        cursor = data.get("cursor")
        if not cursor:
            break

    return images

# ---------- RUN ----------
catalog_objects = fetch_catalog_items()
print(f"Pulled {len(catalog_objects)} catalog objects")

items = {
    obj["id"]: obj
    for obj in catalog_objects
    if obj.get("type") == "ITEM"
}

print(f"Items: {len(items)}")

images = fetch_catalog_images()
print(f"Images: {len(images)}")

# ---------- MAP ITEMS → IMAGE URLS ----------
item_images = []

for item_id, item in items.items():
    item_data = item.get("item_data", {})
    item_name = item_data.get("name")

    # Normalize image references
    image_ids = []

    if "image_ids" in item_data and item_data["image_ids"]:
        image_ids.extend(item_data["image_ids"])

    if "image_id" in item_data and item_data["image_id"]:
        image_ids.append(item_data["image_id"])

    for image_id in image_ids:
        image_obj = images.get(image_id)
        if not image_obj:
            continue

        image_url = image_obj.get("image_data", {}).get("url")
        if not image_url:
            continue

        item_images.append({
            "item_id": item_id,
            "item_name": item_name,
            "image_id": image_id,
            "image_url": image_url
        })

print(f"Resolved {len(item_images)} item → image mappings")

# ---------- EXPORT ----------
with open("square_item_images_old_store.csv", "w", newline="") as f:
    writer = csv.DictWriter(
        f,
        fieldnames=["item_id", "item_name", "image_id", "image_url"]
    )
    writer.writeheader()
    writer.writerows(item_images)

print("Exported square_item_images_old_store.csv")