import requests
import time
import json

# --- Configuration ---
NOTION_TOKEN = "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"  # Replace with your actual Notion integration token
PARENT_PAGE_ID = "2e088f42854480248289deb383da3818" # Replace with the ID of the Notion page where you want to create the databases
NOTION_VERSION = "2022-06-28"
NOTION_API_BASE_URL = "https://api.notion.com/v1"

HEADERS = {
    "Authorization": f"Bearer {NOTION_TOKEN}",
    "Notion-Version": NOTION_VERSION,
    "Content-Type": "application/json",
}

# --- Database Schemas ---
# Define basic properties for each database. Relations will be added in a second phase.

DATABASE_SCHEMAS = {
    "Product Master": {
        "title": [{"type": "text", "text": {"content": "Product Master"}}],
        "properties": {
            "Name": {"title": {}},
            "Beschreibung": {"rich_text": {}},
            "Spezifikationen": {"rich_text": {}},
            "Layer": {"multi_select": {"options": [{"name": "Cleaning"}, {"name": "Service"}, {"name": "Security"}]}},
        }
    },
    "Sector & Persona Master": {
        "title": [{"type": "text", "text": {"content": "Sector & Persona Master"}}],
        "properties": {
            "Name": {"title": {}},
            "RoboPlanet-Definition": {"rich_text": {}},
            "Personas": {"multi_select": {"options": []}}, # Options can be added later if known
            "Pains": {"rich_text": {}},
            "Gains": {"rich_text": {}},
            "Probing Questions": {"rich_text": {}},
        }
    },
    "Messaging Matrix": {
        "title": [{"type": "text", "text": {"content": "Messaging Matrix"}}],
        "properties": {
            "Name": {"title": {}},
            "Satz 1": {"rich_text": {}},
            "Satz 2": {"rich_text": {}},
            "Voice Script": {"rich_text": {}},
        }
    },
    "Competitive Radar": {
        "title": [{"type": "text", "text": {"content": "Competitive Radar"}}],
        "properties": {
            "Wettbewerber": {"title": {}},
            "News": {"url": {}},
            "Blogposts": {"url": {}},
            "Kill-Argumente": {"rich_text": {}},
            "Technische Specs": {"rich_text": {}},
        }
    },
    "Enrichment Factory & RevOps": {
        "title": [{"type": "text", "text": {"content": "Enrichment Factory & RevOps"}}],
        "properties": {
            "Account Name": {"title": {}},
            "Umsatz": {"number": {"format": "euro"}},
            "Mitarbeiter": {"number": {"format": "number"}},
            "Ansprechpartner": {"rich_text": {}},
            "Job Titel": {"rich_text": {}},
            "Klassifizierung": {"multi_select": {"options": []}}, # Options can be added later if known
            "Outbound Metriken": {"rich_text": {}},
        }
    },
    "The Brain": {
        "title": [{"type": "text", "text": {"content": "The Brain"}}],
        "properties": {
            "Titel": {"title": {}},
            "Lösungsfragmente": {"rich_text": {}},
            "Quelle": {"url": {}},
        }
    },
    "GTM Workspace": {
        "title": [{"type": "text", "text": {"content": "GTM Workspace"}}],
        "properties": {
            "Kampagnen Name": {"title": {}},
        }
    }
}

# --- Database Relations (Phase B) ---
# Define which databases relate to each other.
# The keys are the database names, and the values are lists of (property_name, related_database_name) tuples.
DATABASE_RELATIONS = {
    "Product Master": [
        ("Sector Master", "Sector & Persona Master"),
        ("Messaging Matrix", "Messaging Matrix"),
        ("The Brain", "The Brain"),
        ("GTM Workspace", "GTM Workspace"),
    ],
    "Sector & Persona Master": [
        ("Product Master", "Product Master"),
        ("Messaging Matrix", "Messaging Matrix"),
    ],
    "Messaging Matrix": [
        ("Product Master", "Product Master"),
        ("Sector Master", "Sector & Persona Master"),
    ],
    "The Brain": [
        ("Product Master", "Product Master"),
    ],
    "GTM Workspace": [
        ("Product Master", "Product Master"),
    ],
    # Competitive Radar and Enrichment Factory & RevOps do not have explicit relations to other *created* databases based on the document's "Notion Datenbank-Relationen" section.
}

# --- Helper Functions ---

def create_notion_database(parent_page_id, db_name, properties):
    print(f"Attempting to create database: {db_name}")
    create_url = f"{NOTION_API_BASE_URL}/databases"
    payload = {
        "parent": {"type": "page_id", "page_id": parent_page_id},
        "title": DATABASE_SCHEMAS[db_name]["title"],
        "properties": properties,
    }
    try:
        response = requests.post(create_url, headers=HEADERS, json=payload)
        response.raise_for_status() # Raise an exception for HTTP errors
        db_data = response.json()
        db_id = db_data["id"]
        print(f"Successfully created database '{db_name}' with ID: {db_id}")
        return db_id
    except requests.exceptions.HTTPError as e:
        print(f"HTTP Error creating database {db_name}: {e}")
        if response is not None:
            print(f"Response content: {response.text}")
        return None
    except Exception as e:
        print(f"An unexpected error occurred while creating database {db_name}: {e}")
        return None

def update_notion_database_relations(database_id, relations_to_add, created_db_ids):
    print(f"Attempting to update relations for database ID: {database_id}")
    update_url = f"{NOTION_API_BASE_URL}/databases/{database_id}"
    properties_to_add = {}
    for prop_name, related_db_name in relations_to_add:
        if related_db_name in created_db_ids:
            related_db_id = created_db_ids[related_db_name]
            properties_to_add[prop_name] = {
                "relation": {
                    "database_id": related_db_id,
                    "dual_property": {} # Notion automatically creates a dual property
                }
            }
        else:
            print(f"Warning: Related database '{related_db_name}' not found among created databases. Skipping relation for '{prop_name}'.")

    if not properties_to_add:
        print(f"No relations to add for database ID: {database_id}")
        return False

    payload = {
        "properties": properties_to_add
    }
    try:
        response = requests.patch(update_url, headers=HEADERS, json=payload)
        response.raise_for_status()
        print(f"Successfully updated relations for database ID: {database_id}")
        return True
    except requests.exceptions.HTTPError as e:
        print(f"HTTP Error updating relations for database ID {database_id}: {e}")
        if response is not None:
            print(f"Response content: {response.text}")
        return False
    except Exception as e:
        print(f"An unexpected error occurred while updating relations for database ID {database_id}: {e}")
        return False

def main():
    if NOTION_TOKEN == "YOUR_NOTION_TOKEN" or PARENT_PAGE_ID == "YOUR_PARENT_PAGE_ID":
        print("ERROR: Please update NOTION_TOKEN and PARENT_PAGE_ID in the script before running.")
        return

    created_db_ids = {}

    print("--- Phase A: Creating Databases ---")
    for db_name, schema in DATABASE_SCHEMAS.items():
        db_id = create_notion_database(PARENT_PAGE_ID, db_name, schema["properties"])
        if db_id:
            created_db_ids[db_name] = db_id
            print(f"Waiting 15 seconds for Notion to index database '{db_name}'...")
            time.sleep(15)
        else:
            print(f"Failed to create database: {db_name}. Aborting Phase A.")
            return

    print("\n--- Phase B: Establishing Relations ---")
    if not created_db_ids:
        print("No databases were created in Phase A. Cannot establish relations.")
        return

    for db_name, relations_config in DATABASE_RELATIONS.items():
        if db_name in created_db_ids:
            db_id = created_db_ids[db_name]
            print(f"Processing relations for '{db_name}' (ID: {db_id})...")
            if update_notion_database_relations(db_id, relations_config, created_db_ids):
                print(f"Waiting 15 seconds after updating relations for '{db_name}'...")
                time.sleep(15)
            else:
                print(f"Failed to update relations for: {db_name}. Continuing with other databases.")
        else:
            print(f"Warning: Database '{db_name}' not found in created IDs. Skipping relation updates.")

    print("\n--- Setup Complete ---")
    print("Please ensure your Notion integration has access to the parent page and its sub-pages in Notion UI.")
    print("Created database IDs:")
    for name, id_val in created_db_ids.items():
        print(f"- {name}: {id_val}")

if __name__ == "__main__":
    main()
