"""Command-line interface for carbcor."""

from __future__ import annotations

import argparse
import sys

import pandas as pd

from carbcor import __version__
from carbcor.core import (
    BASE_URL,
    apply_carbon_corrections,
    debug_response,
    discover_form,
    get_carbon_correction,
)


def main(argv: list[str] | None = None) -> None:
    parser = argparse.ArgumentParser(
        prog="carbcor",
        description=(
            "Apply Placco et al. (2014) carbon evolutionary corrections "
            "for metal-poor stars."
        ),
    )
    parser.add_argument(
        "--version", action="version", version=f"%(prog)s {__version__}"
    )
    sub = parser.add_subparsers(dest="command")

    # ── single-star query ────────────────────────────────────────────────
    p_query = sub.add_parser("query", help="Query correction for one star.")
    p_query.add_argument("logg", type=float, help="Surface gravity log(g)")
    p_query.add_argument("feh", type=float, help="Metallicity [Fe/H]")
    p_query.add_argument("cfe", type=float, help="Carbon ratio [C/Fe]")

    # ── batch from CSV ───────────────────────────────────────────────────
    p_batch = sub.add_parser("batch", help="Apply corrections to a CSV file.")
    p_batch.add_argument("input", help="Input CSV file path")
    p_batch.add_argument(
        "-o", "--output", default=None,
        help="Output CSV path (default: print to stdout)",
    )
    p_batch.add_argument("--logg-col", default="logg")
    p_batch.add_argument("--feh-col", default="feh")
    p_batch.add_argument("--cfe-col", default="cfe")
    p_batch.add_argument(
        "--delay", type=float, default=0.5,
        help="Delay between requests in seconds (default: 0.5)",
    )

    # ── diagnostics ──────────────────────────────────────────────────────
    sub.add_parser("discover", help="Show form structure on the website.")
    sub.add_parser("debug", help="Send a test query and show raw response.")

    args = parser.parse_args(argv)

    if args.command == "query":
        result = get_carbon_correction(args.logg, args.feh, args.cfe)
        if result["status"] == "success":
            print(
                f"Input:     log(g)={args.logg}  "
                f"[Fe/H]={args.feh}  [C/Fe]={args.cfe}"
            )
            print(f"Corrected: [C/Fe] = {result['cfe_corrected']:.4f}")
            print(f"Delta:     +{result['correction']:.4f}")
        else:
            print(f"Error: {result['message']}", file=sys.stderr)
            sys.exit(1)

    elif args.command == "batch":
        df = pd.read_csv(args.input)
        result = apply_carbon_corrections(
            df,
            logg_col=args.logg_col,
            feh_col=args.feh_col,
            cfe_col=args.cfe_col,
            delay=args.delay,
        )
        if args.output:
            result.to_csv(args.output, index=False)
            print(f"Saved to {args.output}")
        else:
            print(result.to_csv(index=False))

    elif args.command == "discover":
        discover_form(verbose=True)

    elif args.command == "debug":
        debug_response()

    else:
        parser.print_help()


if __name__ == "__main__":
    main()
