"""
Download one F277W I2D mosaic from MAST as proof-of-pipeline.
"""
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

# Direct file download by URI
uri = 'mast:JWST/product/jw04598001001_04101_00005_nrcalong_i2d.fits'
out_dir = 'JWST_GO4598_F277W'
os.makedirs(out_dir, exist_ok=True)

print(f"Downloading {uri} ...")
result = Observations.download_file(uri, local_path=os.path.join(out_dir, 'jw04598001001_04101_00005_nrcalong_i2d.fits'))
print(f"Result: {result}")

# Verify
target = os.path.join(out_dir, 'jw04598001001_04101_00005_nrcalong_i2d.fits')
if os.path.exists(target):
    size_mb = os.path.getsize(target) / 1e6
    print(f"Downloaded: {target} ({size_mb:.1f} MB)")

    # Inspect FITS structure
    from astropy.io import fits
    with fits.open(target) as hdul:
        print()
        print("FITS structure:")
        hdul.info()
        # Primary header
        print()
        print("Primary header key items:")
        h = hdul[0].header
        keys = ['TELESCOP', 'INSTRUME', 'FILTER', 'TARG_RA', 'TARG_DEC',
                'OBJECT', 'PROGRAM', 'OBSERVTN', 'VISIT', 'BUNIT', 'EXPTIME',
                'EFFEXPTM', 'NAXIS1', 'NAXIS2']
        for k in keys:
            if k in h:
                print(f"  {k}: {h[k]}")
        # WCS info from SCI extension
        if len(hdul) > 1:
            print()
            print("SCI extension header WCS items:")
            sh = hdul[1].header if hdul[1].name == 'SCI' else hdul[0].header
            wcs_keys = ['CRVAL1', 'CRVAL2', 'CRPIX1', 'CRPIX2', 'CDELT1', 'CDELT2',
                        'CTYPE1', 'CTYPE2', 'NAXIS1', 'NAXIS2', 'BUNIT']
            for k in wcs_keys:
                if k in sh:
                    print(f"  {k}: {sh[k]}")
            if hdul[1].name == 'SCI':
                data = hdul[1].data
                if data is not None:
                    print(f"\nSCI data shape: {data.shape}")
                    print(f"SCI data dtype: {data.dtype}")
                    import numpy as np
                    finite = data[np.isfinite(data)]
                    if len(finite) > 0:
                        print(f"SCI finite min/max/mean: {finite.min():.4g} / {finite.max():.4g} / {finite.mean():.4g}")
else:
    print("Download did not produce expected file.")
