# This file is part of the Astrometry.net suite.
# Licensed under a 3-clause BSD style license - see LICENSE

# Creates brightstars.fits and brightstars-data.c
# from the HIP catalog from Vizier
# and the Stellarium skycultures.

# Stellarium is licensed under GPL v2+.

# I fetched hip.fits by visiting
# http://vizier.u-strasbg.fr/viz-bin/VizieR-3?-source=I/239/hip_main
# and selecting FITS binary output, and columns HIP, Vmag, _RA.icrs, _DE.icrs
# the latter of which are ICRS, epoch 2000 coordinates.

def main():
    from astrometry.util.fits import fits_table
    import numpy as np
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument('skyculture', help='Stellarium skyculture/XXX/star-names.fab file')
    parser.add_argument('hip', help='Hipparcos catalog')
    parser.add_argument('out', help='Output filename')
    parser.add_argument('--brightstars', help='brightstars-data.c output filename')
    parser.add_argument('--multi', default=False, action='store_true', help='Keep multiple names (default is keep the first one only')
    parser.add_argument('--letternames', type=str, help='Stellarium stars/default/name.fab data file')
    opt = parser.parse_args()

    starnames = opt.skyculture
    hipfn = opt.hip

    H = fits_table(hipfn)
    H.ra  = H.get('_ra_icrs')
    H.dec = H.get('_de_icrs')

    hipmap = dict([(h,i) for i,h in enumerate(H.hip)])

    got_hipnums = {}
    bright = fits_table()
    bright.hip = []
    bright.ra = []
    bright.dec = []
    bright.vmag = []
    bright.names = []
    bright.letternames = []

    filenames = [(starnames, False)]
    if opt.letternames:
        filenames.append((opt.letternames, True))

    for fn,is_letter in filenames:
        f = open(fn, 'r')
        for line in f.readlines():
            line = line.strip()
            if line.startswith('#'):
                continue
            if len(line) == 0:
                continue
            hipnum = line.split('|')[0]
            hipnum = int(hipnum)
            if not is_letter:
                startstr = '_("'
                i0 = line.index(startstr) + len(startstr)
                endstr = '")'
                i1 = line.index(endstr)
                name = line[i0:i1]
            else:
                name = line.split('|')[1]
                name = name.replace('_', ' ')
            name = name.encode('ascii', 'backslashreplace')
            hipi = hipmap[hipnum]
            print('Name', name, 'HIP', hipnum, H.ra[hipi], H.dec[hipi])
            ra = H.ra[hipi]
            if not np.isfinite(ra):
                print('Null HIP entry?')
                continue

            if hipnum in got_hipnums:
                i = got_hipnums[hipnum]
                print('Appending to previous: HIP', bright.hip[i], 'names',
                      bright.letternames[i], 'and', bright.names[i])
                if is_letter:
                    bright.letternames[i].append(name)
                else:
                    bright.names[i].append(name)
                continue

            bright.hip.append(hipnum)
            bright.ra.append(H.ra[hipi])
            bright.dec.append(H.dec[hipi])
            bright.vmag.append(H.vmag[hipi])
            if is_letter:
                bright.letternames.append([name])
                bright.names.append([])
            else:
                bright.letternames.append([])
                bright.names.append([name])

            i = len(bright.hip)-1
            assert(hipnum not in got_hipnums)
            assert(bright.hip[i] == hipnum)
            got_hipnums[hipnum] = i

    if opt.multi:
        bright.names = [b' / '.join(n) for n in bright.names]
        bright.letternames = [b' / '.join(n) for n in bright.letternames]
    else:
        bright.names = [n[0] if len(n) else b'' for n in bright.names]
        bright.letternames = [n[0] if len(n) else b'' for n in bright.letternames]

    bright.to_np_arrays()
    bright.rename('letternames', 'name1')
    bright.rename('names', 'name2')
    bright.writeto(opt.out)

    if opt.brightstars:
        f = open(opt.brightstars, 'wb')
        f.write(b'// Autogenerated by brightstars.py\n')
        f.write(b'{')
        for b in bright:
            f.write((b'{ "%s", "%s", %f, %f, %f},\n' % (b.name1, b.name2, b.ra, b.dec, b.vmag)))
        f.write(b'}')
        f.close()


if __name__ == '__main__':
    main()
