"""Create a read-only PostgreSQL user for the chatbot API."""
import psycopg2

conn = psycopg2.connect(
    host="172.16.2.190",
    port=15433,
    user="pgvector",
    password="password",
    dbname="postgres"
)
conn.autocommit = True
cur = conn.cursor()

# 1. Create user
cur.execute("CREATE USER canifa_bot_readonly WITH PASSWORD 'CanifaBot@R3adOnly2026'")
print("User canifa_bot_readonly created")

# 2. Grant connect to database
cur.execute("GRANT CONNECT ON DATABASE postgres TO canifa_bot_readonly")
print("CONNECT granted on database postgres")

# 3. Grant usage on schema public
cur.execute("GRANT USAGE ON SCHEMA public TO canifa_bot_readonly")
print("USAGE granted on schema public")

# 4. Grant SELECT on langgraph + n8n history tables
tables = [
    "langgraph_chat_histories",
    "n8n_chat_histories",
    "n8n_chat_histories_dev",
]
for t in tables:
    cur.execute(f"GRANT SELECT ON public.{t} TO canifa_bot_readonly")
    print(f"SELECT granted on public.{t}")

cur.close()
conn.close()
print("Done! Read-only user ready.")
