'''
  ____   ___  _     _ _       
 / ___| / _ \| |   (_) |_ ___ 
 \___ \| | | | |   | | __/ _ \
  ___) | |_| | |___| | ||  __/
 |____/ \__\_\_____|_|\__\___|
                              
Script to set the config (smart version - doesn't overwrite existing data)
/usr/bin/python3 /var/www/moduleair_pro_4g/sqlite/set_config_smart.py

in case of readonly error:
sudo chmod 777 /var/www/moduleair_pro_4g/sqlite/sensors.db
'''

import sqlite3

# Connect to (or create if not existent) the database
conn = sqlite3.connect("/var/www/moduleair_pro_4g/sqlite/sensors.db")
cursor = conn.cursor()

print(f"Connected to database")

def safe_insert_config(key, value, value_type):
    """Insert config only if it doesn't exist"""
    cursor.execute("SELECT COUNT(*) FROM config_table WHERE key = ?", (key,))
    if cursor.fetchone()[0] == 0:
        cursor.execute(
            "INSERT INTO config_table (key, value, type) VALUES (?, ?, ?)",
            (key, value, value_type)
        )
        print(f"Added config: {key} = {value}")
    else:
        print(f"Config already exists: {key}")

def safe_insert_envea_sonde(connected, port, name, coefficient):
    """Insert envea sonde only if it doesn't exist (check by port and name)"""
    cursor.execute("SELECT COUNT(*) FROM envea_sondes_table WHERE port = ? AND name = ?", (port, name))
    if cursor.fetchone()[0] == 0:
        cursor.execute(
            "INSERT INTO envea_sondes_table (connected, port, name, coefficient) VALUES (?, ?, ?, ?)",
            (1 if connected else 0, port, name, coefficient)
        )
        print(f"Added envea sonde: {name} on {port}")
    else:
        print(f"Envea sonde already exists: {name} on {port}")

# Check if tables are empty (first run)
cursor.execute("SELECT COUNT(*) FROM config_table")
config_count = cursor.fetchone()[0]

cursor.execute("SELECT COUNT(*) FROM config_scripts_table")
scripts_count = cursor.fetchone()[0]

cursor.execute("SELECT COUNT(*) FROM envea_sondes_table")
sondes_count = cursor.fetchone()[0]

# If this is the first run (all tables empty), clear and do fresh install
if config_count == 0 and scripts_count == 0 and sondes_count == 0:
    print("First run detected - setting up initial configuration...")
    # Clear existing data (if any)
    cursor.execute("DELETE FROM config_table")
    cursor.execute("DELETE FROM config_scripts_table")
    cursor.execute("DELETE FROM envea_sondes_table")
    print("Tables cleared for fresh setup")
else:
    print("Existing configuration detected - will only add missing entries...")


# Insert general configurations
config_entries = [
    ("modem_config_mode", "0", "bool"),
    ("deviceID", "XXXX", "str"),
    ("npm_5channel", "0", "bool"),
    ("BME280", "0", "bool"),
    ("SFA30", "0", "bool"),
    ("MHZ19", "0", "bool"),
    ("envea", "0", "bool"),
    ("latitude_raw", "0", "int"),
    ("longitude_raw", "0", "int"),
    ("latitude_precision", "0", "int"),
    ("longitude_precision", "0", "int"),
    ("deviceName", "ModuleAir-proXXX", "str"),
    ("SaraR4_baudrate", "115200", "int"),
    ("NPM_solo_port", "/dev/ttyAMA5", "str"),
    ("sshTunnel_port", "59228", "int"),
    ("SARA_general_status", "connected", "str"),
    ("SARA_SIM_status", "connected", "str"),
    ("SARA_network_status", "connected", "str"),
    ("SARA_signal_quality", "22", "int"),
    ("SARA_neworkID", "20810", "int"),
    ("WIFI_status", "connected", "str"),
    ("send_uSpot", "0", "bool"),
    ("windMeter", "0", "bool"),
    ("modem_version", "XXX", "str"),
    # Add new config entries here
    ("matrix_display", "0", "bool"),
    ("matrix_display_bool", "0", "bool"),
    ("matrix_display_type", "split_reveal", "str"),
    ("matrix_brightness", "100", "int")
]

print("\nProcessing general configurations...")
for key, value, value_type in config_entries:
    safe_insert_config(key, value, value_type)

# Insert envea sondes
envea_sondes = [
    (False, "ttyAMA4", "h2s", 4),
    (False, "ttyAMA3", "no2", 1),
    (False, "ttyAMA2", "o3", 1),
    # Add new sondes here if needed
]

print("\nProcessing envea sondes...")
for connected, port, name, coefficient in envea_sondes:
    safe_insert_envea_sonde(connected, port, name, coefficient)

# Commit and close the connection
conn.commit()
conn.close()

print("\nDatabase updated successfully!")