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 get_page_id(db_id, title_col, title_val):
    url = f"https://api.notion.com/v1/databases/{db_id}/query"
    payload = {
        "filter": {
            "property": title_col,
            "title": {"equals": title_val}
        }
    }
    resp = requests.post(url, headers=HEADERS, json=payload)
    if resp.status_code == 200:
        results = resp.json().get("results", [])
        if results:
            return results[0] 
    return None

def update_page(page_id, properties):
    url = f"https://api.notion.com/v1/pages/{page_id}"
    payload = {"properties": properties}
    resp = requests.patch(url, headers=HEADERS, json=payload)
    if resp.status_code == 200:
        print(f"✅ Updated page {page_id}")
    else:
        print(f"❌ Error updating {page_id}: {resp.text}")

def append_text(current_text, new_text):
    if not current_text:
        return new_text
    if new_text in current_text:
        return current_text 
    return f"{current_text}\n\n[Auto-Update]: {new_text}"

# --- DATA TO UPDATE (Example) ---
PERSONA_UPDATES = {
    "Wirtschaftlicher Entscheider": "10-25% Reduktion Personalkosten\n15-30% höhere Gästezufriedenheit (Hypothese)",
    "Operativer Entscheider": "20-40% Entlastung bei Routineaufgaben\n100% Abdeckung Reinigungszyklen",
    "Infrastruktur-Verantwortlicher": "20-30% schnellere Integration\n80-90% weniger Ausfallzeiten",
    "Innovations-Treiber": "10-20% höhere Servicekapazität\nSteigerung Upselling 5-10%"
}

def run_updates():
    print("--- Starting Notion Updates ---")
    db_personas = find_db_id("Personas")
    if db_personas:
        for role, kpi_text in PERSONA_UPDATES.items():
            page = get_page_id(db_personas, "Role", role)
            if page:
                update_page(page['id'], {
                    "KPIs": {"rich_text": [{"text": {"content": kpi_text}}]}
                })
    
    # Industries update logic omitted for brevity in restore, but structure is here.

if __name__ == "__main__":
    run_updates()
