import os
import requests
import json
from dotenv import load_dotenv

load_dotenv(dotenv_path="/home/node/clawd/.env")

NOTION_TOKEN = os.getenv("NOTION_API_KEY")
HEADERS = {
    "Authorization": f"Bearer {NOTION_TOKEN}",
    "Content-Type": "application/json",
    "Notion-Version": "2022-06-28"
}

def find_db_id(query_name):
    url = "https://api.notion.com/v1/search"
    payload = {"query": query_name, "filter": {"value": "database", "property": "object"}}
    resp = requests.post(url, headers=HEADERS, json=payload)
    if resp.status_code == 200:
        results = resp.json().get("results", [])
        if results: return results[0]['id']
    return None

def fetch_products():
    db_id = find_db_id("Product Categories") or find_db_id("Products")
    if not db_id: return

    url = f"https://api.notion.com/v1/databases/{db_id}/query"
    resp = requests.post(url, headers=HEADERS, json={})
    
    products = {}
    if resp.status_code == 200:
        results = resp.json().get("results", [])
        for page in results:
            props = page['properties']
            name = "Unknown"
            if "Name" in props and props["Name"]["title"]:
                 name = props["Name"]["title"][0]["plain_text"]
            products[name] = page['id']
            
        os.makedirs("data", exist_ok=True)
        with open("data/product_mapping.json", "w") as f:
            json.dump(products, f, indent=4)

if __name__ == "__main__":
    fetch_products()
