"""
CLEAN CALCULATION - NO ERRORS VERSION
"""

import numpy as np

# بيانات حقيقية
current_data = {
    1: {-20: 10.522, 20: 10.960, 40: 11.179},
    2: {-20: 10.253, 20: 10.680, 40: 10.894},
    3: {-20: 10.099, 20: 10.520, 40: 10.730},
    4: {-20: 8.928, 20: 9.300, 40: 9.486},
}

offsets = {1: -0.960, 2: -0.680, 3: -0.520, 4: 0.700}

print("="*60)
print("حساب α الفردي - إصدار مصحح")
print("="*60)

alpha_values = {}

for sensor_id in range(1, 5):
    I_minus20 = current_data[sensor_id][-20] + offsets[sensor_id]
    I_20 = current_data[sensor_id][20] + offsets[sensor_id]
    I_40 = current_data[sensor_id][40] + offsets[sensor_id]
    
    # حساب α
    alpha = (I_40 - I_minus20) / (I_20 * 60.0)
    alpha_values[sensor_id] = alpha
    
    print(f"\nالمجس #{sensor_id}:")
    print(f"  I(-20°C) = {I_minus20:.4f} mA")
    print(f"  I(20°C)  = {I_20:.4f} mA")
    print(f"  I(40°C)  = {I_40:.4f} mA")
    print(f"  α = {alpha:.6f} → {alpha*100:.3f}%/°C")

print("\n" + "="*60)
print("كود C النظيف:")
print("="*60)

c_code = """// ============================================================================
// ELECTRIC FIELD CALIBRATION - CLEAN VERSION
// ============================================================================

#include <stdint.h>
#include <math.h>

// Current offsets at 20°C (mA)
const float CURRENT_OFFSETS[4] = {-0.960f, -0.680f, -0.520f, 0.700f};

// Individual temperature coefficients (1/°C) - CALCULATED
const float ALPHA_COEFFICIENTS[4] = {
    %.6ff,  // Sensor 1: %.3f%%/°C
    %.6ff,  // Sensor 2: %.3f%%/°C
    %.6ff,  // Sensor 3: %.3f%%/°C
    %.6ff   // Sensor 4: %.3f%%/°C
};

// Field gains at 20°C
const float FIELD_GAINS[4] = {1.0981f, 1.0650f, 1.0510f, 0.9280f};

// Physical conversion constant
const float K_SENSOR = 90.91f;

// ================= CALIBRATION FUNCTION ====================

float calibrate_field(uint8_t sensor_idx, float measured_current, float temperature)
{
    if (sensor_idx > 3) return 0.0f;  // Safety check
    
    float offset = CURRENT_OFFSETS[sensor_idx];
    float alpha  = ALPHA_COEFFICIENTS[sensor_idx];
    float gain   = FIELD_GAINS[sensor_idx];
    
    // 1) Apply offset
    float I_corrected = measured_current + offset;
    
    // 2) Apply temperature compensation
    if (temperature != 20.0f) {
        float dT = temperature - 20.0f;
        I_corrected *= (1.0f + alpha * dT);
    }
    
    // 3) Convert to field
    float field = I_corrected * K_SENSOR * gain;
    
    return field;
}

// ================= SIMPLE INTERFACE ====================

float get_field_reading(uint8_t sensor_id, float current_mA, float temp_C)
{
    // sensor_id is 1-based, convert to 0-based
    uint8_t idx = sensor_id - 1;
    return calibrate_field(idx, current_mA, temp_C);
}
"""

# إضافة القيم الحقيقية
print(c_code % (
    alpha_values[1], alpha_values[1]*100,
    alpha_values[2], alpha_values[2]*100,
    alpha_values[3], alpha_values[3]*100,
    alpha_values[4], alpha_values[4]*100
))

print("\n" + "="*60)
print("اختبار بسيط:")
print("="*60)

# محاكاة بسيطة
class CleanCalibrator:
    def __init__(self):
        self.offsets = [-0.960, -0.680, -0.520, 0.700]
        self.alphas = [alpha_values[1], alpha_values[2], alpha_values[3], alpha_values[4]]
        self.gains = [1.0981, 1.0650, 1.0510, 0.9280]
        self.k = 90.91
    
    def calibrate(self, sensor_id, current, temp=20.0):
        idx = sensor_id - 1
        I_corr = current + self.offsets[idx]
        
        if temp != 20.0:
            I_corr *= (1.0 + self.alphas[idx] * (temp - 20.0))
        
        return I_corr * self.k * self.gains[idx]

# اختبار
cal = CleanCalibrator()

print("\nاختبار المجس #1:")
for temp, current in [(-20, 10.522), (20, 10.960), (40, 11.179)]:
    result = cal.calibrate(1, current, temp)
    expected = 1000
    error = ((result - expected) / expected) * 100
    print(f"  {temp}°C: {result:.1f} V/m (خطأ: {error:.1f}%)")

print("\nاختبار المجس #4:")
for temp, current in [(-20, 8.928), (20, 9.300), (40, 9.486)]:
    result = cal.calibrate(4, current, temp)
    expected = 1000
    error = ((result - expected) / expected) * 100
    print(f"  {temp}°C: {result:.1f} V/m (خطأ: {error:.1f}%)")

print("\n" + "="*60)
print("🎯 الخطوة التالية:")
print("="*60)
print("1. تطبيق هذا الكود النظيف")
print("2. إذا بقي خطأ >5% → نضيف معامل تربيعي γ")
print("3. الميدان سيعطينا بيانات حقيقية للتحسين")
