#!/usr/bin/env python3
"""
GSED Batch Search — Python client example

Requires: pip install requests

Endpoint: POST {BASE_URL}/batch_search
  - multipart/form-data
  - fields: coord_sys, radius (arcmin, <=30), d (kpc), targets (text)
  - optional: file (targets file; server merges with targets text)
  - success: application/x-tar stream (one .fits + one .txt per target, plus manifest.txt)
  - limits: <= 500 targets; radius <= 30 arcmin
"""

from __future__ import annotations

import argparse
import io
import tarfile
from pathlib import Path

import requests

DEFAULT_BASE_URL = "https://nadc.china-vo.org/data/gsed"


def batch_search(
    base_url: str,
    targets_text: str | None = None,
    targets_file: str | Path | None = None,
    coord_sys: str = "equatorial",
    radius_arcmin: float = 6.0,
    d_kpc: float = 2.0,
    out_tar: str | Path = "gsed_batch.tar",
    timeout: float | None = None,
) -> Path:
    """
    Call batch search and save the returned tar archive.

    Prefer putting the full target list in ``targets_text`` (or a file whose
    content you load into ``targets_text``). If both text and file are sent,
    the server concatenates them; the web UI uses the text box as the source
    of truth.
    """
    if radius_arcmin <= 0 or radius_arcmin > 30:
        raise ValueError("radius must be > 0 and <= 30 arcmin")

    url = base_url.rstrip("/") + "/batch_search"
    data = {
        "coord_sys": coord_sys,  # equatorial | galactic
        "radius": str(radius_arcmin),
        "d": str(d_kpc),
        "targets": targets_text or "",
    }

    files = None
    fh = None
    try:
        if targets_file is not None:
            path = Path(targets_file)
            fh = path.open("rb")
            files = {"file": (path.name, fh, "text/plain")}

        with requests.post(
            url,
            data=data,
            files=files,
            stream=True,
            timeout=timeout,
        ) as resp:
            if resp.status_code != 200:
                # error body is usually JSON: {"error": "..."}
                raise RuntimeError(
                    f"HTTP {resp.status_code}: {resp.text[:500]}"
                )

            out_path = Path(out_tar)
            with out_path.open("wb") as out:
                for chunk in resp.iter_content(chunk_size=1024 * 256):
                    if chunk:
                        out.write(chunk)
            return out_path
    finally:
        if fh is not None:
            fh.close()


def list_tar_members(tar_path: str | Path) -> list[str]:
    names: list[str] = []
    with tarfile.open(tar_path, mode="r:*") as tar:
        for m in tar.getmembers():
            names.append(m.name)
    return names


def extract_tar(tar_path: str | Path, dest_dir: str | Path) -> None:
    dest = Path(dest_dir)
    dest.mkdir(parents=True, exist_ok=True)
    with tarfile.open(tar_path, mode="r:*") as tar:
        tar.extractall(path=dest)


def main() -> None:
    parser = argparse.ArgumentParser(description="GSED batch search client example")
    parser.add_argument(
        "--base-url",
        default=DEFAULT_BASE_URL,
        help=f"API base URL (default: {DEFAULT_BASE_URL})",
    )
    parser.add_argument(
        "--targets-file",
        default=None,
        help="Path to targets txt/csv (optional if --targets is set)",
    )
    parser.add_argument(
        "--targets",
        default=None,
        help='Inline targets text, e.g. "47.119 4.645\\n47.2 4.7 6"',
    )
    parser.add_argument(
        "--coord-sys",
        choices=("equatorial", "galactic"),
        default="equatorial",
    )
    parser.add_argument("--radius", type=float, default=6.0, help="default radius in arcmin (<=30)")
    parser.add_argument("--d", type=float, default=2.0, help="distance in kpc for fitting curve")
    parser.add_argument("-o", "--output", default="gsed_batch.tar", help="output tar path")
    parser.add_argument(
        "--extract-to",
        default=None,
        help="If set, extract the tar into this directory after download",
    )
    args = parser.parse_args()

    targets_text = args.targets
    if targets_text is None and args.targets_file is None:
        # minimal demo list (Equatorial)
        targets_text = (
            "# example targets\n"
            "ra dec radius\n"
            "47.119 4.645\n"
            "47.119, 4.645, 6\n"
        )

    # If a file is given and no inline text, load file into targets_text
    # so the request matches the web UI rule (text box is authoritative).
    if targets_text is None and args.targets_file is not None:
        targets_text = Path(args.targets_file).read_text(encoding="utf-8", errors="ignore")
        targets_file = None
    else:
        targets_file = args.targets_file

    out = batch_search(
        base_url=args.base_url,
        targets_text=targets_text,
        targets_file=targets_file,
        coord_sys=args.coord_sys,
        radius_arcmin=args.radius,
        d_kpc=args.d,
        out_tar=args.output,
        timeout=None,  # large batches can take a long time
    )
    print(f"Saved: {out.resolve()}")
    members = list_tar_members(out)
    print(f"Members ({len(members)}):")
    for name in members[:20]:
        print(f"  {name}")
    if len(members) > 20:
        print(f"  ... and {len(members) - 20} more")

    if args.extract_to:
        extract_tar(out, args.extract_to)
        print(f"Extracted to: {Path(args.extract_to).resolve()}")


if __name__ == "__main__":
    main()
