import psycopg2
from psycopg2 import sql

def init_db(host, user, password, dbname):
    # Connect to default postgres to create the db if not exists
    conn = psycopg2.connect(host=host, user=user, password=password, dbname='postgres')
    conn.autocommit = True
    cur = conn.cursor()
    
    cur.execute("SELECT 1 FROM pg_database WHERE datname = %s", (dbname,))
    exists = cur.fetchone()
    if not exists:
        cur.execute(f"CREATE DATABASE {dbname} OWNER postgres")
        print(f"Database {dbname} created with owner postgres.")
    else:
        cur.execute(f"ALTER DATABASE {dbname} OWNER TO postgres")
        print(f"Database {dbname} owner set to postgres.")
    
    cur.close()
    conn.close()

    # Connect to the new db to create tables
    conn = psycopg2.connect(host=host, user=user, password=password, dbname=dbname)
    cur = conn.cursor()
    
    cur.execute("""
        CREATE TABLE IF NOT EXISTS modules (
            id SERIAL PRIMARY KEY,
            technical_name VARCHAR(100) UNIQUE NOT NULL,
            display_name VARCHAR(200),
            summary TEXT,
            author VARCHAR(100),
            version VARCHAR(50),
            category VARCHAR(100),
            dependencies TEXT[],
            path TEXT,
            last_generated TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        );
    """)
    # Asegurar que el dueño de la tabla sea postgres
    try:
        cur.execute("ALTER TABLE modules OWNER TO postgres")
    except Exception as e:
        print(f"Aviso: No se pudo cambiar el dueño de la tabla 'modules' automáticamente: {e}")
        
    conn.commit()
    print("Tables initialized/updated.")
    cur.close()
    conn.close()

if __name__ == "__main__":
    init_db('localhost', 'initium20', 'straconX260706', 'strx_docs')
