import psycopg2
import json
import os

ip_device = os.getenv("ip_device")
db_server = json.loads(os.getenv("dist_servs"))[ip_device]

# Parámetros de conexión a la base de datos
file_path = os.path.join(os.getcwd(), "json_files/DirectorioCSICT.json")

# json_file_path = ".\json_files\DirectorioCSICT.json"
with open(file_path, 'r', encoding='utf-8-sig') as f:
    json_content = json.load(f)

conn = psycopg2.connect(
    host=db_server,
    port=5432,
    database="aldeas_inteligentes",
    user="postgres",
    password="Shala55951254"
)

cursor = conn.cursor()

cursor.execute("DROP TABLE IF EXISTS dir_csict;")

create_table_query = """
CREATE TABLE dir_csict (
id SERIAL PRIMARY KEY,
json_data JSONB
);"""

cursor.execute(create_table_query)

# Insertar el contenido JSON en la tabla
insert_query = "INSERT INTO dir_csict (json_data) VALUES (%s);"
cursor.execute(insert_query, (json.dumps(json_content),))

# guardar cambios
conn.commit()
# Cerrar la conexión
cursor.close()
conn.close()
print(f'Servidor actualizado en directorio centros sict')
