import psycopg2
import bcrypt
import json
import uuid

try:
    conn = psycopg2.connect(
        host="192.168.1.85", 
        port=5432, 
        user="admin", 
        password="admin_password_2026", 
        dbname="lubrication_crm"
    )
    cur = conn.cursor()
    hash_pw = bcrypt.hashpw(b"admin123", bcrypt.gensalt()).decode("utf-8")
    permissions_json = json.dumps(["view", "edit"])
    new_uuid = str(uuid.uuid4())
    
    cur.execute(
        """
        INSERT INTO users (id, username, password_hash, role, permissions, is_active)
        VALUES (%s, %s, %s, %s, %s, true)
        ON CONFLICT (username) DO UPDATE SET password_hash=EXCLUDED.password_hash
        """, 
        (new_uuid, "admin", hash_pw, "admin", permissions_json)
    )
    conn.commit()
    print("Admin user inserted/updated via SQL script.")
except Exception as e:
    print(f"Database error: {e}")
finally:
    if 'cur' in locals():
        cur.close()
    if 'conn' in locals():
        conn.close()
