# step4_shake.py — the earthquake signal.
# A seismometer hears two waves. The P wave is fast and small. The S wave comes
# later and does the damage. The gap between them says how far away the quake is.
# New here: distance_km(), warning_seconds(), intensity() and shake_score().

import math

P_SPEED = 5.0           # km per second, a P wave in granite
S_SPEED = 3.0           # km per second, about 60 percent of the P wave
KM_PER_GAP_SECOND = 7.5  # from the two speeds: 5 x 3 / (5 - 3). Many books round it to 8.


def ramp(value, low, high):
    """0 below low, 1 above high, a straight line between them."""
    if value <= low:
        return 0.0
    if value >= high:
        return 1.0
    return (value - low) / (high - low)


def distance_km(gap_seconds):
    """Seconds between the P wave and the S wave, times 7.5, is the distance."""
    return gap_seconds * KM_PER_GAP_SECOND


def warning_seconds(km):
    """The P wave arrives first. The time before the S wave is the warning time."""
    return km / S_SPEED - km / P_SPEED


def intensity(magnitude, km):
    """How strong the shaking feels, from 1 to 12.
    A simple classroom rule, fitted to the 2025 quake. Real agencies use better ones."""
    value = 1.5 * magnitude - 3 * math.log10(max(km, 1)) + 1.5
    return max(1.0, min(12.0, value))


def shake_score(magnitude, km):
    """Intensity 3 is a weak shake. Intensity 8 breaks buildings."""
    return ramp(intensity(magnitude, km), 3, 8)


def main():
    # 28 March 2025, magnitude 7.7, Sagaing Fault, Myanmar
    magnitude = 7.7
    for city, km in [("Mandalay", 16), ("Chiang Mai", 480), ("Bangkok", 1000)]:
        print(f"{city:11} {km:5} km   shaking {intensity(magnitude, km):4.1f}   "
              f"warning {warning_seconds(km):5.1f} s   "
              f"score {shake_score(magnitude, km):.2f}")

    # A seismometer in Chiang Mai hears the P wave, then the S wave 64 seconds later.
    print("P to S gap 64 s -> about", round(distance_km(64)), "km away")


if __name__ == "__main__":
    main()
