#! /usr/bin/env python3

import argparse

from xmet.db   import Database
from xmet.raob import RAOBReader
from xmet.igra import IGRAStation

parser = argparse.ArgumentParser(
    description = 'Ingest RAOB soundings'
)

parser.add_argument('--quiet',   action='store_true', help='Suppress output')
parser.add_argument('--dry-run', action='store_true', help='Do not actually ingest data')

parser.add_argument('db',                            help='XMET SQLite3 database')
parser.add_argument('raob-sounding-file', nargs='+', help='RAOB sounding file')

args = parser.parse_args()

db = Database.connect(args.db)

if not args.dry_run:
    db.execute('begin transaction')

for path in getattr(args, 'raob-sounding-file'):
    if not args.quiet:
        print(f"Ingesting sounding file {path}")

    for sounding in RAOBReader.each_sounding_from_file(path):
        station = IGRAStation.find_station(db, sounding.station)

        if station is not None:
            sounding.station = station.code

        if not args.dry_run:
            db.add(sounding)

        for sample in sounding.samples:
            sample.sounding_id = sounding.id

            if not args.dry_run:
                db.add(sample)

if not args.dry_run:
    db.commit()