"""
CALCULATE INDIVIDUAL α FOR EACH SENSOR - FIXED VERSION
"""

import numpy as np

print("="*70)
print("🎯 CALCULATE INDIVIDUAL α FOR EACH SENSOR")
print("="*70)

# البيانات الحقيقية
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("\n📊 حساب α لكل مجس:")
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]
    
    α = (I_40 - I_minus20) / (I_20 * 60)
    α_percent = α * 100
    
    alpha_values[sensor_id] = α
    
    print(f"\nالمجس #{sensor_id}:")
    print(f"  I(-20°C) = {current_data[sensor_id][-20]:.3f} + {offsets[sensor_id]:+.3f} = {I_minus20:.3f} mA")
    print(f"  I(20°C)  = {current_data[sensor_id][20]:.3f} + {offsets[sensor_id]:+.3f} = {I_20:.3f} mA")
    print(f"  I(40°C)  = {current_data[sensor_id][40]:.3f} + {offsets[sensor_id]:+.3f} = {I_40:.3f} mA")
    print(f"  α = ({I_40:.3f} - {I_minus20:.3f}) / ({I_20:.3f} × 60)")
    print(f"  α = {α:.6f} (عامل/°س)")
    print(f"  α = {α_percent:.3f} %/°س")

print("\n" + "="*70)
print("💻 كود C المحدث:")
print("="*70)

# إنشاء كود C بدون f-strings معقدة
c_code = """// ============================================================================
// ELECTRIC FIELD CALIBRATION - WITH INDIVIDUAL α PER SENSOR
// ============================================================================

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

// Array indices: 0=Sensor1, 1=Sensor2, 2=Sensor3, 3=Sensor4

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

// INDIVIDUAL α coefficients (calculated from actual measurements)
const float ALPHA_COEFFICIENTS[4] = {"""

# إضافة قيم α
for sensor_id in range(1, 5):
    α = alpha_values[sensor_id]
    α_pct = α * 100
    c_code += f"\n    {α:.6f}f,  // Sensor {sensor_id}: {α_pct:.3f}%/°C"

c_code += """
};

// 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;

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

float calibrate_field(uint8_t sensor_idx, float measured_current, float temperature) {
    // Convert 1-based to 0-based if needed
    if (sensor_idx > 0) sensor_idx = sensor_idx - 1;
    
    // 1. Apply offset
    float offset = CURRENT_OFFSETS[sensor_idx];
    float I_corrected = measured_current + offset;
    
    // 2. Apply INDIVIDUAL temperature compensation
    if (temperature != 20.0f) {
        float alpha = ALPHA_COEFFICIENTS[sensor_idx];
        float temp_factor = 1.0f + (alpha * (temperature - 20.0f));
        I_corrected *= temp_factor;
    }
    
    // 3. Convert to field and apply gain
    float field = I_corrected * K_SENSOR * FIELD_GAINS[sensor_idx];
    
    return field;
}

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

float get_field_reading(uint8_t sensor_id, float current_ma, float temp_c) {
    return calibrate_field(sensor_id, current_ma, temp_c);
}
"""

print(c_code)

# حفظ الكود
with open("final_calibration_individual_alpha.c", "w") as f:
    f.write(c_code)

print("\n✅ تم حفظ الكود: final_calibration_individual_alpha.c")

print("\n" + "="*70)
print("🧪 اختبار α الفردي:")
print("="*70)

# اختبار بسيط
class SimpleCalibrator:
    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 = SimpleCalibrator()

print("\n📊 نتائج الاختبار:")
print("المجس | الدرجة | التيار | النتيجة | الخطأ")
print("-"*50)

# بيانات الاختبار
tests = [
    (1, -20, 10.522, 1000),
    (1, 20, 10.960, 1000),
    (1, 40, 11.179, 1000),
    (4, -20, 8.928, 1000),
    (4, 20, 9.300, 1000),
    (4, 40, 9.486, 1000),
]

errors = []
for sensor_id, temp, current, expected in tests:
    result = cal.calibrate(sensor_id, current, temp)
    error = ((result - expected) / expected) * 100
    errors.append(abs(error))
    
    print(f"{sensor_id:4} | {temp:5}°س | {current:6.3f} | {result:7.1f} | {error:5.1f}%")

max_error = max(errors)
print(f"\n📈 أقصى خطأ: {max_error:.1f}%")

if max_error < 2.0:
    print("🎉 نجاح! الخطأ < 2%")
    print("✅ النظام جاهز للميدان!")
elif max_error < 5.0:
    print("⚠️  مقبول للميدان (خطأ < 5%)")
    print("🔧 يمكن تحسينه بالمعايرة الميدانية")
else:
    print("❌ يحتاج تحسين إضافي")

print("\n" + "="*70)
print("🚀 جاهز للتطبيق!")
print("="*70)
