"""Extract the fixed GW170817 photometry subset used by the kilonova tutorial.

Input: phot_table.dat from the arXiv source of Villar et al. 2017
(arXiv:1710.11576v2, ApJL 851, L21). Download the source archive from
https://arxiv.org/e-print/1710.11576 and unpack it, then run

    python extract_gw170817_photometry.py path/to/phot_table.dat

The script keeps detections in g, r, i, z, J, H, K and Ks that Villar et al.
mark as used in their fit ("*") and not flagged as outliers ("O"). It writes
gw170817-photometry.csv next to this script and prints the SHA-256 digests of
the input table and the output file. Magnitudes are AB and are NOT corrected
for Milky Way extinction (Villar et al. 2017, Section 2).
"""
import csv
import hashlib
import re
import sys
from pathlib import Path

KEPT_FILTERS = {'g': 'g', 'r': 'r', 'i': 'i', 'z': 'z', 'J': 'J', 'H': 'H', 'K': 'K', 'Ks': 'K'}
MERGER_MJD = 57982.528524  # GW170817 merger time, 2017-08-17 12:41:04 UTC


def parse_rows(text):
    for line in text.splitlines():
        if not re.match(r'^\s*5\d{4}\.\d+\s*&', line):
            continue
        cells = [cell.strip() for cell in line.replace('\\&', 'and').rstrip().rstrip('\\').split('&')]
        if len(cells) < 10:
            raise ValueError(f'Unexpected row: {line}')
        mjd, phase, instrument, telescope, band, magnitude, error, shift, reference, note = cells[:10]
        reference = re.sub(r'\\citeauthor\{([^}]*)\}', r'\1', reference).strip()
        yield dict(mjd=mjd, phase=phase, instrument=instrument, telescope=telescope, filter=band,
                   magnitude=magnitude, error=error, shift=shift, reference=reference, note=note.strip())


def keep(row):
    flags = row['note'].upper().replace(' ', '').split(',')
    return (row['filter'] in KEPT_FILTERS and '*' in flags and 'O' not in flags
            and re.fullmatch(r'\d+\.\d+', row['magnitude']) and re.fullmatch(r'\d+\.\d+', row['error']))


def main():
    source = Path(sys.argv[1])
    raw = source.read_bytes()
    rows = [row for row in parse_rows(raw.decode('utf-8')) if keep(row)]
    rows.sort(key=lambda row: (float(row['mjd']), row['filter']))
    output = Path(__file__).with_name('gw170817-photometry.csv')
    with output.open('w', newline='') as handle:
        writer = csv.writer(handle, lineterminator='\n')
        writer.writerow(['days_since_merger', 'mjd', 'band', 'filter', 'ab_mag', 'ab_mag_error', 'telescope', 'instrument', 'reference_key'])
        for row in rows:
            days = float(row['mjd']) - MERGER_MJD
            writer.writerow([f'{days:.3f}', row['mjd'], KEPT_FILTERS[row['filter']], row['filter'], row['magnitude'], row['error'],
                             row['telescope'], row['instrument'], row['reference']])
    print('input sha256', hashlib.sha256(raw).hexdigest())
    print('output sha256', hashlib.sha256(output.read_bytes()).hexdigest())
    print('rows', len(rows))


if __name__ == '__main__':
    main()
