# -*- coding:utf-8 -*-
"""
This script demonstrates how to generate NLLoc OBS phase pick files from
QuakeMigrate output (using the picks generated by the autopicker).

"""

import pathlib

from quakemigrate.export import to_obspy, to_nlloc

# QM run directory (containing locate, detect and trigger directories)
run_dir = ""

output_dir = pathlib.Path(run_dir / "nonlinloc_obs")
output_dir.mkdir(parents=True, exist_ok=True)

# Read QM output into an obspy catalog. This reads locations, magnitudes,
# amplitudes, modelled and auto-picks, as well as QM-specific attributes such
# as the coalescence values. It assigns the event resource ID as the QM
# Event ID (e.g. 20140807000001000 for an event 1 second after midnight on
# 7th August 2014). This ID is determined from the event trigger time, and is
# unique within a given QM run. "units" should be the same as those used in the
# LUT - they are used for converting the depths and uncertainties into km (as
# this is the convention for obspy / QuakeML catalogues).
cat = to_obspy.read_quakemigrate(run_dir, units="km")

# Loop through events and write a NonLinLoc obs file for each.
for event in cat:
    filename = f"{event.resource_id.id}.nonlinloc"
    to_nlloc.nlloc_obs(event, str(output_dir / filename), autopick=True)
