#!/usr/bin/env python3
"""Fix Neo4j schema - add missing relationships ASKED_ABOUT, WORKS_ON"""

import requests
import json

NEO4J_URL = "http://localhost:7474/db/neo4j/tx/commit"
AUTH = ("neo4j", "DaarionNeo4j2026!")
HEADERS = {"Content-Type": "application/json"}

def run_query(statement):
    """Execute a single Cypher statement"""
    payload = {"statements": [{"statement": statement}]}
    resp = requests.post(NEO4J_URL, auth=AUTH, headers=HEADERS, json=payload)
    data = resp.json()
    if data.get("errors"):
        print(f"ERROR: {data['errors']}")
        return None
    return data

# Step 1: Add telegram_user_id alias to all User nodes
print("1. Adding telegram_user_id to User nodes...")
run_query("""
    MATCH (u:User) 
    WHERE u.telegram_id IS NOT NULL AND u.telegram_user_id IS NULL
    SET u.telegram_user_id = u.telegram_id
    RETURN count(u) as updated
""")

# Step 2: Create Topics
print("2. Creating Topics...")
topics = ["EcoMiner", "BioMiner", "DAO Governance", "Tokenomics", "Staking", "Infrastructure"]
for topic in topics:
    run_query(f"MERGE (t:Topic {{name: '{topic}'}}) RETURN t")
print(f"   Created {len(topics)} topics")

# Step 3: Create Projects
print("3. Creating Projects...")
projects = ["Energy Union", "MicroDAO Daarion", "Helion Agent"]
for project in projects:
    run_query(f"MERGE (p:Project {{name: '{project}', status: 'active'}}) RETURN p")
print(f"   Created {len(projects)} projects")

# Step 4: Create ASKED_ABOUT relationships
print("4. Creating ASKED_ABOUT relationships...")
run_query("""
    MATCH (u:User {username: 'ivantytar'})
    MATCH (t:Topic) WHERE t.name IN ['EcoMiner', 'BioMiner', 'Tokenomics']
    MERGE (u)-[:ASKED_ABOUT {count: 1, last_asked: datetime()}]->(t)
    RETURN count(*) as created
""")

# Step 5: Create WORKS_ON relationships
print("5. Creating WORKS_ON relationships...")
run_query("""
    MATCH (u:User {username: 'ivantytar'})
    MATCH (p:Project) WHERE p.name IN ['Energy Union', 'MicroDAO Daarion']
    MERGE (u)-[:WORKS_ON {role: 'founder', since: datetime()}]->(p)
    RETURN count(*) as created
""")

# Step 6: Create indexes
print("6. Creating indexes...")
run_query("CREATE INDEX topic_name IF NOT EXISTS FOR (t:Topic) ON (t.name)")
run_query("CREATE INDEX project_name IF NOT EXISTS FOR (p:Project) ON (p.name)")
run_query("CREATE INDEX user_telegram_id IF NOT EXISTS FOR (u:User) ON (u.telegram_user_id)")

# Verify
print("\n=== Verification ===")
result = run_query("CALL db.relationshipTypes()")
if result:
    types = [row["row"][0] for row in result.get("results", [{}])[0].get("data", [])]
    print(f"Relationship types: {types}")

result = run_query("""
    MATCH (u:User {username: 'ivantytar'})-[r]->(n)
    RETURN type(r) as rel, labels(n)[0] as node, n.name as name
""")
if result:
    print("\nivantytar's relationships:")
    for row in result.get("results", [{}])[0].get("data", []):
        r = row["row"]
        print(f"  -{r[0]}-> {r[1]}: {r[2]}")

print("\n✅ Neo4j schema updated!")
