import datetime
import time
import json
import os
import arduino

# ---- Config ----
OUTPUT_FILE_TEMP = "/home/cedri/projet-capture-2026-enderbird/accumulation/raspberryPi/donnees_temp.json"
READ_SPEED_ARDUINO = 1         # secondes entre lectures

# ---- Upload Arduino once ----
print("🔄 Uploading Arduino code...")
if not arduino.upload_arduino_code("/home/cedri/projet-capture-2026-enderbird/acquisition/arduino/upload_arduino.sh"):
    exit()

# ---- Detect Arduino port ----
print("🔍 Detecting Arduino port...")
port = arduino.find_arduino_port()
if not port:
    print("❌ Arduino not found, exiting.")
    exit()

# --- Open serial port once ---
ser = arduino.open_arduino_port(port)
if not ser:
    exit()

# --- Loop reading sensor ---
print("⚡ Starting sensor read loop...")
try:
    while True:
        light_value = arduino.read_light_sensor(ser)
        if light_value is None:
            time.sleep(2)
            continue

        entry = {
            "mesure": light_value,
            "moment": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        }

        # --- Append nouvelle lecture dans le fichier temporaire ---
        try:
            # Lire les anciennes lectures temporaires
            if os.path.exists(OUTPUT_FILE_TEMP):
                with open(OUTPUT_FILE_TEMP, "r") as f:
                    temp_data = json.load(f)
            else:
                temp_data = []

            temp_data.append(entry)

            # Sauvegarder à nouveau
            temp_file = OUTPUT_FILE_TEMP + ".tmp"
            with open(temp_file, "w") as f:
                json.dump(temp_data, f, indent=2)
            os.replace(temp_file, OUTPUT_FILE_TEMP)

        except Exception as e:
            print(f"❌ Failed to write temp data: {e}")

        time.sleep(READ_SPEED_ARDUINO)

finally:
    ser.close()