"""
Dynamic Snowstorm with Realistic Electric Fields
Snow Dust Project - Real E-field simulation
"""

import numpy as np
import time

# ==============================================================
# REALISTIC PARAMETERS
# ==============================================================
steps = 20
dt = 0.5  # seconds

# Snowstorm parameters
snow_density = 1e6  # #/m³
particle_diameter = 200e-6  # meters
wavelength = 550e-9  # meters

# Physical constants
epsilon0 = 8.854187817e-12  # F/m
breakdown_threshold = 3e6  # V/m (dry air breakdown)

# TRIBOLECTRIC CONSTANTS (REALISTIC)
k_charge = 1.0e-12  # C (much larger - realistic charge transfer)
alpha = 1.8          # velocity exponent
beta = 2.2           # diameter exponent
gamma = 1.0          # temperature exponent

# ==============================================================
# IMPROVED FUNCTIONS
# ==============================================================
def compute_Q_sca(diameter):
    """Mie scattering efficiency (simplified)"""
    r = diameter / 2
    x = 2 * np.pi * r / wavelength
    
    if x < 1:
        return (8/3) * x**4 * abs((1.31**2 - 1)/(1.31**2 + 2))**2
    elif x < 100:
        return 2.0 * (1 - np.exp(-x/10))
    else:
        return 2.0

def visibility(snow_density, diameter):
    """Calculate visibility from extinction"""
    sigma_ext = compute_Q_sca(diameter) * np.pi * (diameter/2)**2
    beta_ext = snow_density * sigma_ext
    return 3.912 / beta_ext if beta_ext > 0 else float('inf')

def compute_E_field_realistic(diameter, density, wind_speed=15.0, delta_T=5.0):
    """
    REALISTIC triboelectric charging:
    Q = k * v^α * d^β * ΔT^γ
    E = Q_total / (4πε₀r²)
    """
    # Collision velocity (10% of wind speed)
    v_collision = 0.15 * wind_speed
    
    # Single particle charge (in Coulombs)
    Q_single = k_charge * \
              (abs(v_collision) ** alpha) * \
              (diameter ** beta) * \
              (abs(delta_T) ** gamma)
    
    # Space charge density
    space_charge = Q_single * density  # C/m³
    
    # Electric field at 1m distance (simplified)
    E_field = abs(space_charge) / (2 * epsilon0)
    
    return E_field, Q_single

# ==============================================================
# ASCII VISUALIZATION
# ==============================================================
def bar(value, max_value, length=30, char='█'):
    """Create ASCII bar"""
    n = int(min(value/max_value, 1.0) * length)
    return char * n + '░' * (length - n)

def colorize(text, color_code):
    """Add ANSI colors"""
    colors = {
        'red': '\033[91m',
        'green': '\033[92m',
        'yellow': '\033[93m',
        'blue': '\033[94m',
        'magenta': '\033[95m',
        'cyan': '\033[96m',
        'reset': '\033[0m'
    }
    return f"{colors.get(color_code, '')}{text}{colors['reset']}"

# ==============================================================
# MAIN SIMULATION
# ==============================================================
print(colorize("⚡ REALISTIC SNOWSTORM SIMULATION ⚡", "cyan"))
print(colorize("Snow Dust Project - Electric Field Dynamics", "yellow"))
print("=" * 65 + "\n")

# Initialize
time_series = []
visibility_series = []
efield_series = []
risk_series = []

for t in range(steps):
    # Dynamic variations
    current_density = snow_density * np.random.uniform(0.9, 1.1)
    current_diameter = particle_diameter * np.random.uniform(0.95, 1.05)
    
    # Wind speed variations (gusts)
    wind_speed = 15.0 * np.random.uniform(0.8, 1.2)
    delta_T = 5.0 * np.random.uniform(0.5, 1.5)
    
    # Calculate visibility
    vis = visibility(current_density, current_diameter)
    
    # Calculate REALISTIC electric field
    E_field, Q_single = compute_E_field_realistic(
        current_diameter, current_density, wind_speed, delta_T
    )
    
    # Breakdown risk
    risk = min(E_field / breakdown_threshold, 1.0)
    
    # Store for time series
    time_series.append(t * dt)
    visibility_series.append(vis)
    efield_series.append(E_field)
    risk_series.append(risk)
    
    # Polarity (random for visualization)
    polarity = '+' if np.random.rand() > 0.5 else '-'
    
    # Create bars
    vis_bar = bar(vis, 100, 40, '█')  # Max visibility 100m
    efield_bar = bar(E_field, 10000, 40, '⚡')  # Max E-field 10kV/m
    
    # Color code based on values
    if vis < 30:
        vis_display = colorize(f"{vis:.1f} m", "red")
    elif vis < 60:
        vis_display = colorize(f"{vis:.1f} m", "yellow")
    else:
        vis_display = colorize(f"{vis:.1f} m", "green")
    
    if E_field > 5000:
        efield_display = colorize(f"{E_field:.1f} V/m", "red")
        risk_display = colorize(f"{risk*100:.1f}%", "red")
    elif E_field > 1000:
        efield_display = colorize(f"{E_field:.1f} V/m", "yellow")
        risk_display = colorize(f"{risk*100:.1f}%", "yellow")
    else:
        efield_display = colorize(f"{E_field:.1f} V/m", "blue")
        risk_display = colorize(f"{risk*100:.1f}%", "green")
    
    # Display
    print(colorize(f"⏱️  Time: {t*dt:.1f}s | 🌬️  Wind: {wind_speed:.1f} m/s | 🌡️  ΔT: {delta_T:.1f}K", "cyan"))
    print(f"   Density: {current_density:.1e} #/m³ | Diameter: {current_diameter*1e6:.1f} µm")
    print(f"   Visibility: [{vis_bar}] {vis_display}")
    print(f"   E-field:    [{efield_bar}] {efield_display}")
    print(f"   Polarity: {polarity} | Single charge: {Q_single:.2e} C")
    print(f"   ⚡ Breakdown risk: {risk_display}")
    print()
    
    time.sleep(0.3)

# Summary
print(colorize("=" * 65, "cyan"))
print(colorize("📊 SIMULATION SUMMARY:", "bold"))
print(f"   Max visibility: {max(visibility_series):.1f} m")
print(f"   Min visibility: {min(visibility_series):.1f} m")
print(f"   Max E-field: {max(efield_series):.1f} V/m")
print(f"   Max breakdown risk: {max(risk_series)*100:.1f}%")

if max(efield_series) > breakdown_threshold * 0.5:
    print(colorize("   ⚠️  WARNING: High electrostatic risk detected!", "red"))
elif max(efield_series) > breakdown_threshold * 0.1:
    print(colorize("   ⚡ Moderate electrostatic activity", "yellow"))
else:
    print(colorize("   ✅ Low electrostatic activity", "green"))

print(colorize("\n🎯 Snow Dust navigation system: READY", "green"))
