#!/usr/bin/env python
"""Phase 1 step 4: classify RMS HII regions into UC / compact / classical
using CORNISH 5 GHz radio angular sizes + RMS distances.

UC HII: physical diameter <= 0.1 pc (Kurtz 2005 / Wood & Churchwell 1989)
Compact HII: 0.1 < D <= 0.5 pc
Classical/extended: D > 0.5 pc
"""
import numpy as np
from astropy.table import Table
from astropy.coordinates import SkyCoord
import astropy.units as u
from astroquery.vizier import Vizier

LOG = open('uchii_classify.log', 'w')
def p(*a):
    print(*a); print(*a, file=LOG); LOG.flush()

def get_cornish():
    v = Vizier(row_limit=-1)
    # CORNISH-North, Purcell et al. 2013, ApJS 205, 1
    t = v.get_catalogs('J/ApJS/205/1')
    for tt in t:
        p('CORNISH table', tt.meta.get('name'), 'nrows', len(tt), 'cols', tt.colnames)
    return t

def main():
    m = Table.read('master_phase1.fits')
    c = SkyCoord(m['RAJ2000'], m['DEJ2000'], unit=(u.deg, u.deg))
    m['GLON'] = c.galactic.l.deg
    m['GLAT'] = c.galactic.b.deg

    cat = get_cornish()
    # pick the main UCHII/source table (largest, with size column)
    cn = None
    for tt in cat:
        if any('major' in x.lower() or 'diam' in x.lower() or 'size' in x.lower()
               or x in ('amaj','bmaj','Maj') for x in tt.colnames):
            cn = tt; break
    if cn is None:
        cn = max(cat, key=len)
    p('Using CORNISH table:', cn.meta.get('name'), cn.colnames)
    cn.write('cornish_north_raw.fits', overwrite=True)
    LOG.close()

if __name__ == '__main__':
    main()
