"""
Query MAST for HST archival data on Bullet Cluster 1E0657-56.
Target the ACS filters Cha 2025 referenced: F435W, F606W, F775W, F814W, F850LP.
"""
import os, sys, urllib3, requests
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
old_request = requests.Session.request
def _patched(self, *args, **kwargs):
    kwargs['verify'] = False
    return old_request(self, *args, **kwargs)
requests.Session.request = _patched

from astroquery.mast import Observations
try:
    Observations._portal_api_connection.session.verify = False
except Exception:
    pass

# Position-based query at Bullet Cluster center
print("--- HST ACS observations at Bullet Cluster field ---")
obs = Observations.query_criteria(
    obs_collection='HST',
    instrument_name='ACS/WFC',
    target_name=['1E0657-558', '1E0657-56', '1E-0657-56', '1E0657-558.5', 'BULLET-CLUSTER', 'BULLETCLUSTER'],
)
print(f"HST/ACS target-name match: {len(obs)}")

if len(obs) == 0:
    # Fallback: search by coordinates
    from astropy.coordinates import SkyCoord
    import astropy.units as u
    coord = SkyCoord(ra=104.66*u.deg, dec=-55.95*u.deg)
    obs = Observations.query_region(coord, radius=0.1*u.deg)
    # filter to ACS
    mask = (obs['obs_collection'] == 'HST') & (obs['instrument_name'] == 'ACS/WFC')
    obs = obs[mask]
    print(f"Position-based HST/ACS at Bullet Cluster: {len(obs)}")

if len(obs) > 0:
    filters_set = set(str(f) for f in obs['filters'])
    print("Filters present:", sorted(filters_set))
    print("Programs (proposal_id):", sorted(set(str(p) for p in obs['proposal_id'])))
    print("Target names:", sorted(set(str(t) for t in obs['target_name'])))
    obs.write('mast_hst_acs_bullet.csv', format='csv', overwrite=True)
    print(f"\nSaved {len(obs)} obs to mast_hst_acs_bullet.csv")
    # Filter to the 5 specific Cha-cited filters
    target_filters = ['F435W', 'F606W', 'F775W', 'F814W', 'F850LP']
    matched = []
    for row in obs:
        fstr = str(row['filters'])
        if any(tf in fstr for tf in target_filters):
            matched.append(row)
    print(f"Matching Cha-cited filters: {len(matched)} observations")
