"""
Dynamic Snowstorm Simulation with ASCII Visualization
- Shows visibility & E-field as bars in terminal
- Termux-compatible, SciPy-free
"""

import numpy as np
import time

# ==============================================================
# Snowstorm parameters
# ==============================================================
steps = 15
dt = 0.5  # seconds per step

snow_density = 1e6  # #/m³
particle_diameter = 200e-6  # meters
wavelength = 550e-9  # meters
epsilon0 = 8.854e-12
breakdown_threshold = 3e6  # V/m

# ==============================================================
# Functions
# ==============================================================
def compute_Q_sca(diameter):
    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 < 2000:
        Q_ray = (8/3) * x**4 * 0.01
        Q_geo = 2.0
        transition = 1 - np.exp(-0.12 * x)
        return Q_ray * np.exp(-0.08 * x) + Q_geo * transition
    else:
        return 2.0

def visibility(snow_density, diameter):
    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(diameter, density, distance=1.0):
    single_charge = 2.66e-23 * (diameter/200e-6)**1.5
    q_total = single_charge * density
    return q_total / (4 * np.pi * epsilon0 * distance**2) if distance > 0 else 0.0

# ==============================================================
# ASCII visualization helper
# ==============================================================
def bar(value, max_value, length=30, char='#'):
    n = int(min(value/max_value, 1.0) * length)
    return char * n + '-' * (length - n)

# ==============================================================
# Simulation loop
# ==============================================================
print("=== Dynamic Snowstorm ASCII Visualization ===\n")

for t in range(steps):
    # small fluctuations
    snow_density *= np.random.uniform(0.95, 1.05)
    particle_diameter *= np.random.uniform(0.98, 1.02)

    vis = visibility(snow_density, particle_diameter)
    E = compute_E_field(particle_diameter, snow_density)
    risk = min(E / breakdown_threshold, 1.0)

    vis_bar = bar(vis, 100, 30, '#')  # max 100 m visibility
    E_bar = bar(E, 1e3, 30, '*')     # scale E-field for visualization

    polarity = '+' if np.random.rand() > 0.5 else '-'

    print(f"Time {t*dt:.1f}s | Density: {snow_density:.1e} #/m³ | Diameter: {particle_diameter*1e6:.1f} µm")
    print(f"  Visibility: [{vis_bar}] {vis:.1f} m")
    print(f"  E-field:   [{E_bar}] {E:.1f} V/m | Polarity: {polarity} | Breakdown risk: {risk*100:.2f}%\n")

    time.sleep(0.2)

print("Simulation complete.")
