"""
FIELD OPERATION CODE - SIMPLIFIED
For initial field deployment
"""

field_code = """// ============================================================================
// FIELD OPERATION - INITIAL DEPLOYMENT
// Snow Dust Project - Electric Field Monitoring
// ============================================================================

#include <SD.h>
#include <Wire.h>
#include <RTClib.h>

// Sensor configuration
#define NUM_SENSORS 4
#define SAMPLE_RATE 10000  // Hz
#define FIELD_RANGE 20000  // V/m (±20 kV/m)

// Data structure for field readings
typedef struct {
    uint32_t timestamp;
    float sensor_currents[NUM_SENSORS];  // mA
    float temperature;                    // °C
    float humidity;                       // %
    uint8_t system_status;
} FieldReading;

// Global variables
RTC_DS3231 rtc;
File dataFile;
FieldReading currentReading;

// ================= INITIALIZATION ====================

void setup() {
    Serial.begin(115200);
    Wire.begin();
    
    // Initialize RTC
    if (!rtc.begin()) {
        Serial.println("RTC FAILED");
        while(1);
    }
    
    // Initialize SD card
    if (!SD.begin(4)) {
        Serial.println("SD CARD FAILED");
    }
    
    // Create data file
    char filename[20];
    DateTime now = rtc.now();
    sprintf(filename, "DATA_%04d%02d%02d.csv", 
            now.year(), now.month(), now.day());
    
    dataFile = SD.open(filename, FILE_WRITE);
    if (dataFile) {
        dataFile.println("timestamp,temp_C,sensor1_mA,sensor2_mA,sensor3_mA,sensor4_mA");
        dataFile.close();
    }
    
    Serial.println("Field system READY");
}

// ================= DATA COLLECTION ====================

void read_sensors() {
    DateTime now = rtc.now();
    currentReading.timestamp = now.unixtime();
    
    // Read temperature (example)
    currentReading.temperature = 20.0;  // Placeholder
    
    // Read sensor currents (simulated - replace with actual I2C reads)
    for (int i = 0; i < NUM_SENSORS; i++) {
        // Simulated reading: 10 ± 2 mA with some noise
        float base_current = 10.0;
        float variation = random(-200, 200) / 1000.0;  // ±0.2 mA
        float noise = random(-50, 50) / 1000.0;        // ±0.05 mA
        
        currentReading.sensor_currents[i] = base_current + variation + noise;
    }
}

// ================= DATA LOGGING ====================

void log_data() {
    dataFile = SD.open("field_data.csv", FILE_WRITE);
    if (dataFile) {
        dataFile.print(currentReading.timestamp);
        dataFile.print(",");
        dataFile.print(currentReading.temperature);
        
        for (int i = 0; i < NUM_SENSORS; i++) {
            dataFile.print(",");
            dataFile.print(currentReading.sensor_currents[i], 3);
        }
        
        dataFile.println();
        dataFile.close();
    }
}

// ================= FIELD CALIBRATION ====================

void calculate_relative_calibration() {
    // Simple relative calibration
    // Assumption: All sensors should read similar fields
    // Calculate average of all sensors
    float sum = 0;
    for (int i = 0; i < NUM_SENSORS; i++) {
        sum += currentReading.sensor_currents[i];
    }
    float average = sum / NUM_SENSORS;
    
    // Calculate relative factors
    float calibration_factors[NUM_SENSORS];
    for (int i = 0; i < NUM_SENSORS; i++) {
        calibration_factors[i] = average / currentReading.sensor_currents[i];
    }
    
    // Save calibration factors
    File calFile = SD.open("calibration.csv", FILE_WRITE);
    if (calFile) {
        calFile.println("Sensor,Calibration_Factor");
        for (int i = 0; i < NUM_SENSORS; i++) {
            calFile.print(i+1);
            calFile.print(",");
            calFile.println(calibration_factors[i], 6);
        }
        calFile.close();
    }
}

// ================= MAIN LOOP ====================

void loop() {
    static unsigned long lastSample = 0;
    static unsigned long lastCalibration = 0;
    
    // Sample at SAMPLE_RATE
    if (millis() - lastSample >= (1000 / SAMPLE_RATE)) {
        lastSample = millis();
        
        read_sensors();
        log_data();
        
        // Print to serial (for monitoring)
        Serial.print("T:");
        Serial.print(currentReading.temperature);
        Serial.print("C S1:");
        Serial.print(currentReading.sensor_currents[0], 3);
        Serial.print("mA");
        
        // Calculate relative calibration every hour
        if (millis() - lastCalibration >= 3600000) {
            lastCalibration = millis();
            calculate_relative_calibration();
            Serial.println(" [Calibration updated]");
        } else {
            Serial.println();
        }
    }
    
    // Handle serial commands
    if (Serial.available()) {
        char cmd = Serial.read();
        if (cmd == 'c') {
            calculate_relative_calibration();
            Serial.println("Calibration calculated");
        } else if (cmd == 's') {
            // Print status
            Serial.println("System OK - Field monitoring active");
        }
    }
}

// ============================================================================
// FIELD NOTES:
// 1. This is INITIAL deployment code
// 2. Calibration will be refined with field data
// 3. Focus on RELATIVE consistency between sensors
// 4. Absolute calibration comes later
// ============================================================================
"""

print(field_code)

# Save to file
with open("field_operation.ino", "w") as f:
    f.write(field_code)

print("\n✅ Field operation code saved: field_operation.ino")
print("\n📋 DEPLOYMENT COMMANDS:")
print("  • 'c' - Calculate relative calibration")
print("  • 's' - System status")
print("\n🎯 REMEMBER: Collect data FIRST, calibrate LATER")
