"""
ask_a_telescope.py — ask a real space telescope archive for real data.

No account. No password. No key. The data is public.

Install first:
    pip3 install astropy astroquery

Run it:
    python3 ask_a_telescope.py
    python3 ask_a_telescope.py "Orion Nebula"

Krueng AI — krueng.ai/telescope_data.html
"""

import sys

from astroquery.mast import Observations

TARGET = sys.argv[1] if len(sys.argv) > 1 else "M51"


def ask(target):
    """Ask the archive what it has near one object."""
    obs = Observations.query_object(target, radius="0.01 deg")
    print(f"{target}: {len(obs)} observations")
    return obs


def count_missions(obs):
    """Which telescope took how many?"""
    tally = {}
    for row in obs:
        name = str(row["obs_collection"])
        tally[name] = tally.get(name, 0) + 1

    print("\nwho looked at it:")
    for name, n in sorted(tally.items(), key=lambda pair: -pair[1]):
        print(f"  {name:<12} {n:>5}")


def show_pictures(obs):
    """Keep only the Hubble pictures. Show a few."""
    pics = obs[(obs["obs_collection"] == "HST") &
               (obs["dataproduct_type"] == "image")]
    print(f"\nHubble images: {len(pics)}")

    columns = ["instrument_name", "filters", "t_exptime", "obs_id"]
    pics[columns][:5].pprint(max_width=140)
    return pics


def download_one(pics):
    """Get one small file. Preview files are small."""
    products = Observations.get_product_list(pics[:1])
    print(f"\nfiles in one observation: {len(products)}")

    small = products[products["productType"] == "PREVIEW"]
    if len(small) == 0:
        print("no preview in this one — try another observation")
        return

    small.sort("size")
    result = Observations.download_products(small[:1], download_dir="sky")
    print("status:", str(result["Status"][0]))
    print("saved: ", str(result["Local Path"][0]))


if __name__ == "__main__":
    found = ask(TARGET)
    count_missions(found)
    images = show_pictures(found)
    if len(images):
        download_one(images)
    print("\nAll of that was free. Nobody asked who you are.")
