#!/usr/bin/env python3

# first try and import rstt. if that fails, search the environment variables
# for the appropriate path and try and import from there.
try:
    import rstt

# it looks like importing failed. try searching paths from environment variables for the module
except ModuleNotFoundError:
    import os, sys                                                  # import some required modules
    for d in ('RSTT_ROOT', 'RSTT_HOME', 'SLBM_ROOT', 'SLBM_HOME'):  # list of env vars to check, in order
        if os.getenv(d):                                            # if the environmental var is set
            sys.path.append(os.getenv(d) + "/lib")                  # add to the start of the module search path
    
    # try and import rstt again
    try:
        import rstt

    # if it still fails, raise an exception with a helpful error message
    except ModuleNotFoundError as e:
        e.msg += ". Have you set $RSTT_ROOT, $SLBM_ROOT, or installed RSTT with pip?"
        raise e from None


# main program
if __name__ == "__main__":

    # wrap everything in a try-except block
    try:

        # declare the relative path to the model file we're going to be using
        modelPath = "../models/pdu202009Du.geotess"

        # choose an arbitrary phase (Pn, Pg, Sn, or Lg)
        phase = "Pn"

        # arbitrary source (Meteor Crater, AZ)
        srcLatDeg =   35.0274  # latitude (degrees)
        srcLonDeg = -111.0228  # longitude (degrees)
        srcDepKm  =    1.2345  # depth (km)

        # arbitrary receiver (Albuquerque, NM)
        rcvLatDeg =   35.1053  # latitude (degrees)
        rcvLonDeg = -106.6294  # longitude (degrees)
        rcvDepKm  =   -1.6000  # depth (km)

        # convert lat/lon from degrees to radians
        srcLatRad = rstt.deg2rad(srcLatDeg)
        srcLonRad = rstt.deg2rad(srcLonDeg)
        rcvLatRad = rstt.deg2rad(rcvLatDeg)
        rcvLonRad = rstt.deg2rad(rcvLonDeg)

        # instantiate an RSTT object
        slbm = rstt.SlbmInterface()

        # load the velocity model
        slbm.loadVelocityModel(modelPath)

        # create a great circle from source to the receiver
        slbm.createGreatCircle(phase,
            srcLatRad, srcLonRad, srcDepKm,
            rcvLatRad, rcvLonRad, rcvDepKm)

        # get the distance and travel time from source --> receiver
        travelTimeSec = slbm.getTravelTime()   # compute travel time (sec)
        distRad       = slbm.getDistance()     # compute distance (rad)
        distDeg       = rstt.rad2deg(distRad)  # convert radians --> degrees

        # get the travel time uncertainty
        travelTimeUncertSec   = slbm.getTravelTimeUncertainty()    # compute uncertainty
        travelTime1DUncertSec = slbm.getTravelTimeUncertainty1D()  # compute 1D uncertainty

        # print our results
        print(
            "\n" +
            "Python Example\n" +
            "--------------------------------\n" +
            "Distance:            {:7.4f} deg\n".format(distDeg) +
            "Travel Time:         {:7.4f} sec\n".format(travelTimeSec) +
            "Uncertainty:         {:7.4f} sec\n".format(travelTimeUncertSec) +
            "Uncertainty (1D):    {:7.4f} sec\n".format(travelTime1DUncertSec) +
            "\n"
            )

    # catch possible exceptions
    except Exception as e:

        # raise the error we just caught
        raise(e)
