#!/usr/bin/env python

# tar -czvf SGA2025-hosts-dr11-south.tar.gz --transform 's|.*/dr11-south/|dr11-south/|' -T hosts-dr11-south.txt
# tar -czvf SGA2025-hosts-dr11-north.tar.gz --transform 's|.*/dr11-north/|dr11-north/|' -T hosts-dr11-north.txt
#
# SGA2025-mpi --htmlplots --debug --htmldir=/global/cfs/cdirs/cosmo/www/temp/ioannis/SGA2025-hosts --region=dr11-north --galaxylist=19475p3485,15116p2936,19046p4127,20367p5161,19804p4403,19209p5116,20240p5841,18999p6160,19660p6770,18100p5259,17395p5452,15137p7036,11535p4011,03032p2883
SGA2025-mpi --htmlindex --debug --htmldir=/global/cfs/cdirs/cosmo/www/temp/ioannis/SGA2025-hosts --region=dr11-north --galaxylist=19475p3485,15116p2936,19046p4127,20367p5161,19804p4403,19209p5116,20240p5841,18999p6160,19660p6770,18100p5259,17395p5452,15137p7036,11535p4011,03032p2883
#
# SGA2025-mpi --htmlplots --debug --htmldir=/global/cfs/cdirs/cosmo/www/temp/ioannis/SGA2025-hosts --region=dr11-south --galaxylist=19972m2102,19581m1742,19228m1141,17974m1903,15183p1036,18718p2282,15806p2767,15116p2936,11925p1439,11548p1680,27716m6698,31302m6920,35361m3610,35594m3195,00351m2317,00385m2144,11282m6818,04956m6649,07355m5336,07424m4280,03944m6133,04421m5457,02626m4359,05002m5218,05330m5041,09254m3410,07660m3195,02377m4143,08177m2067,02739p3259,03351p2787,01684p1668,03032p2883
#
SGA2025-mpi --htmlindex --debug --htmldir=/global/cfs/cdirs/cosmo/www/temp/ioannis/SGA2025-hosts --region=dr11-south --galaxylist=19972m2102,19581m1742,19228m1141,17974m1903,15183p1036,18718p2282,15806p2767,15116p2936,11925p1439,11548p1680,27716m6698,31302m6920,35361m3610,35594m3195,00351m2317,00385m2144,11282m6818,04956m6649,07355m5336,07424m4280,03944m6133,04421m5457,02626m4359,05002m5218,05330m5041,09254m3410,07660m3195,02377m4143,08177m2067,02739p3259,03351p2787,01684p1668,03032p2883


import numpy as np
import fitsio
from astropy.table import Table
from astrometry.libkd.spherematch import match_radec
from SGA.SGA import get_galaxy_galaxydir
from SGA.coadds import REGIONBITS


version = 'v1.5'

hosts = Table.read('host_list_250925.txt', format='ascii')
sga = Table(fitsio.read(f'SGA2025-beta-parent-{version}.fits', 'PARENT'))

m1, m2, _ = match_radec(hosts['RA'], hosts['Dec'], sga['RA'], sga['DEC'], 30./3600.)
msga = sga[m2]
msga.meta['EXTNAME'] = 'PARENT'
print(f'Matched {len(msga)}/{len(hosts)} hosts to the SGA-2025.')

outfile = f'SGA2025-beta-parent-{version}-hosts.fits'
msga.write(outfile, overwrite=True)

for region in ['dr11-north', 'dr11-south']:

    I = msga['REGION'] & REGIONBITS[region] != 0
    print(f'Matched {np.sum(I)}/{len(msga)} hosts to the SGA-2025 {region}')

    cat = msga[I]
    cat = cat[cat['GROUP_PRIMARY']]
    print(','.join(cat['GROUP_NAME']))

    _, galdir = get_galaxy_galaxydir(cat, region=region, datadir='/pscratch/sd/i/ioannis/SGA2025-v1.5')
    with open(f'hosts-{region}.txt', 'w') as F:
        for gdir in galdir:
            F.write(f'{gdir}\n')
