#!/usr/bin/env python3
"""
SNOWSTORM SIMULATION WITH REAL ELECTRIC FIELDS
Final corrected version with realistic physics
"""

import numpy as np
import time

# ============================================
# REALISTIC TRIBOLECTRIC PARAMETERS
# Based on scientific literature
# ============================================
k_charge = 1.0e-9      # MUCH LARGER: 1e-9 C (nanocoulombs)
alpha = 2.5            # Strong velocity dependence
beta = 3.0             # Strong diameter dependence  
gamma = 1.5            # Temperature dependence

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

# ============================================
# CORRECTED E-FIELD CALCULATION
# ============================================
def compute_realistic_E_field(diameter, density, wind_speed=15.0, delta_T=5.0):
    """
    REAL TRIBOLECTRIC CHARGING in snowstorms
    Q = k * v^α * d^β * ΔT^γ
    E = ρ / (2ε₀) where ρ = Q * n
    """
    # Real collision velocity (20-30% of wind speed in storms)
    v_coll = 0.25 * wind_speed
    
    # SINGLE PARTICLE CHARGE (in Coulombs)
    Q_single = k_charge * \
              (v_coll ** alpha) * \
              (diameter ** beta) * \
              (delta_T ** gamma)
    
    # Convert to practical units for display
    Q_single_pC = Q_single * 1e12  # picoCoulombs
    
    # SPACE CHARGE DENSITY (C/m³)
    rho = Q_single * density
    
    # ELECTRIC FIELD from space charge (uniform cloud approximation)
    # E = ρ * L / (2ε₀) where L = characteristic length
    L = 10.0  # meters (storm cloud thickness)
    E_field = rho * L / (2 * epsilon0)
    
    return E_field, Q_single_pC, rho

# ============================================
# VISIBILITY CALCULATION
# ============================================
def compute_visibility(density, diameter):
    """Simplified visibility from Mie scattering"""
    # Scattering cross section approximation
    sigma_sca = 2.0 * np.pi * (diameter/2)**2  # Geometric optics limit
    beta_ext = density * sigma_sca
    return 3.912 / beta_ext if beta_ext > 0 else 1000.0

# ============================================
# VISUALIZATION
# ============================================
def colored_bar(value, max_val, length=40):
    """Create colored ASCII bar"""
    ratio = min(value / max_val, 1.0)
    filled = int(ratio * length)
    
    # Choose color based on value
    if ratio < 0.3:
        color = '\033[92m'  # Green
        char = '░'
    elif ratio < 0.7:
        color = '\033[93m'  # Yellow
        char = '▒'
    else:
        color = '\033[91m'  # Red
        char = '▓'
    
    bar = color + char * filled + '\033[0m' + ' ' * (length - filled)
    return bar

def format_scientific(value, unit=""):
    """Format with appropriate prefix"""
    if abs(value) >= 1e6:
        return f"{value/1e6:.2f} M{unit}"
    elif abs(value) >= 1e3:
        return f"{value/1e3:.2f} k{unit}"
    elif abs(value) >= 1:
        return f"{value:.2f} {unit}"
    elif abs(value) >= 1e-3:
        return f"{value*1e3:.2f} m{unit}"
    elif abs(value) >= 1e-6:
        return f"{value*1e6:.2f} µ{unit}"
    else:
        return f"{value:.2e} {unit}"

# ============================================
# MAIN SIMULATION
# ============================================
def main():
    print("\033[96m" + "="*70 + "\033[0m")
    print("\033[95m⚡ REAL SNOWSTORM ELECTROSTATICS ⚡\033[0m")
    print("\033[94mSnow Dust Navigation System - Final Physics Model\033[0m")
    print("\033[96m" + "="*70 + "\033[0m\n")
    
    # Simulation parameters
    duration = 30  # seconds
    dt = 0.5       # time step
    
    # Initial conditions
    base_density = 1e6    # particles/m³
    base_diameter = 200e-6  # meters (200 µm)
    
    results = []
    
    for t in np.arange(0, duration, dt):
        # Dynamic storm variations
        density = base_density * np.random.uniform(0.8, 1.3)
        diameter = base_diameter * np.random.uniform(0.9, 1.2)
        wind_speed = 20.0 * np.random.uniform(0.7, 1.4)  # Gusty winds
        delta_T = 8.0 * np.random.uniform(0.5, 1.5)      # Temperature gradient
        
        # Calculate physics
        visibility = compute_visibility(density, diameter)
        E_field, Q_pC, rho = compute_realistic_E_field(diameter, density, wind_speed, delta_T)
        
        # Breakdown risk
        risk_ratio = E_field / breakdown_threshold
        risk_percent = min(risk_ratio * 100, 100)
        
        # Store results
        results.append({
            'time': t,
            'visibility': visibility,
            'E_field': E_field,
            'risk': risk_percent,
            'density': density,
            'diameter': diameter * 1e6,  # to µm
            'wind': wind_speed,
            'Q_pC': Q_pC
        })
        
        # Display
        print(f"\033[93m⏱️  Time: {t:.1f}s | 🌬️  Wind: {wind_speed:.1f} m/s | 🌡️  ΔT: {delta_T:.1f}K\033[0m")
        print(f"   📊 Density: {format_scientific(density, '#/m³')} | Diameter: {diameter*1e6:.1f} µm")
        print(f"   👁️  Visibility: {colored_bar(visibility, 100)} {visibility:.1f} m")
        print(f"   ⚡ E-field:    {colored_bar(E_field, 10000)} {format_scientific(E_field, 'V/m')}")
        print(f"   🔋 Charge/particle: {Q_pC:.1f} pC | Space charge: {format_scientific(rho, 'C/m³')}")
        
        # Risk warning
        if risk_percent > 50:
            print(f"   \033[91m⚠️  HIGH RISK: Breakdown probability {risk_percent:.1f}%\033[0m")
        elif risk_percent > 20:
            print(f"   \033[93m⚠️  MODERATE RISK: {risk_percent:.1f}%\033[0m")
        else:
            print(f"   \033[92m✅ Low risk: {risk_percent:.1f}%\033[0m")
        
        print()
        time.sleep(0.2)
    
    # Statistics
    print("\033[96m" + "="*70 + "\033[0m")
    print("\033[95m📈 SIMULATION STATISTICS:\033[0m")
    
    max_E = max(r['E_field'] for r in results)
    max_risk = max(r['risk'] for r in results)
    min_vis = min(r['visibility'] for r in results)
    max_Q = max(r['Q_pC'] for r in results)
    
    print(f"   Peak E-field: {format_scientific(max_E, 'V/m')}")
    print(f"   Maximum risk: {max_risk:.1f}%")
    print(f"   Minimum visibility: {min_vis:.1f} m")
    print(f"   Maximum particle charge: {max_Q:.1f} pC")
    
    # Navigation system assessment
    if max_E > 1000:
        print(f"\n\033[92m🎯 SNOW DUST NAVIGATION: OPERATIONAL\033[0m")
        print("   Electric field detection: ✅ SUFFICIENT FOR NAVIGATION")
        if max_E > 5000:
            print("   Signal strength: ✅ STRONG")
        else:
            print("   Signal strength: ✅ MODERATE")
    else:
        print(f"\n\033[93m🎯 SNOW DUST NAVIGATION: MARGINAL\033[0m")
        print("   Electric field detection: ⚠️  WEAK SIGNAL")
    
    print("\033[96m" + "="*70 + "\033[0m")

if __name__ == "__main__":
    main()
