"""Command line interface for lasertram."""

from __future__ import annotations

import argparse
import sys
from pathlib import Path

from lasertram import __version__


DOCS_URL = "https://vsc.code-pages.usgs.gov/petro/tools/lasertram/"
MANUSCRIPT_URL = "https://doi.org/10.1016/j.acags.2025.100225"

EPILOG = f"Documentation: {DOCS_URL}\n" f"Manuscript:    {MANUSCRIPT_URL}"


def build_parser() -> argparse.ArgumentParser:
    """Build the top-level argument parser.

    Returns
    -------
    argparse.ArgumentParser
        Configured parser with ``preprocess`` sub-command.
    """
    parser = argparse.ArgumentParser(
        prog="lasertram",
        description="LaserTRAM: a tool for processing LA-ICP-MS data.",
        epilog=EPILOG,
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    parser.add_argument(
        "-v",
        "--version",
        action="version",
        version=f"lasertram {__version__}",
    )

    subparsers = parser.add_subparsers(dest="command")

    # --- preprocess sub-command ---
    preprocess = subparsers.add_parser(
        "preprocess",
        help="Preprocess a folder of raw LA-ICP-MS .csv files into LaserTRAM format.",
        epilog=EPILOG,
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    preprocess.add_argument(
        "directory",
        type=str,
        help="Path to the folder containing raw .csv files.",
    )
    preprocess.add_argument(
        "-t",
        "--type",
        dest="quad_type",
        choices=["thermo", "agilent"],
        default="thermo",
        help="Quadrupole type: 'thermo' or 'agilent' (default: thermo).",
    )

    output_group = preprocess.add_mutually_exclusive_group()
    output_group.add_argument(
        "--csv",
        dest="output_csv",
        metavar="FILE",
        type=str,
        default=None,
        help="Save output to a CSV file.",
    )
    output_group.add_argument(
        "--xlsx",
        dest="output_xlsx",
        metavar="FILE",
        type=str,
        default=None,
        help="Save output to an Excel (.xlsx) file.",
    )
    output_group.add_argument(
        "--clipboard",
        action="store_true",
        default=False,
        help="Copy output to the system clipboard.",
    )

    return parser


def cmd_preprocess(args: argparse.Namespace) -> None:
    """Execute the ``preprocess`` sub-command.

    Parameters
    ----------
    args : argparse.Namespace
        Parsed command-line arguments.
    """
    from lasertram.helpers.preprocessing import make_lt_ready_folder

    folder = Path(args.directory).resolve()
    if not folder.is_dir():
        print(f"Error: '{args.directory}' is not a valid directory.", file=sys.stderr)
        sys.exit(1)

    df = make_lt_ready_folder(folder, args.quad_type)

    if args.output_csv:
        out = Path(args.output_csv)
        df.to_csv(out, index=False)
        print(f"Preprocessed data saved to {out}")
    elif args.output_xlsx:
        out = Path(args.output_xlsx)
        df.to_excel(out, index=False)
        print(f"Preprocessed data saved to {out}")
    elif args.clipboard:
        df.to_clipboard(index=False)
        print("Preprocessed data copied to clipboard.")
    else:
        # Default: save as csv named after the folder
        out = folder.parent / f"{folder.name}-LT_ready.csv"
        df.to_csv(out, index=False)
        print(f"Preprocessed data saved to {out}")


def main() -> None:
    """Entry point for the ``lasertram`` CLI."""
    parser = build_parser()
    args = parser.parse_args()

    if args.command is None:
        parser.print_help()
        sys.exit(0)

    if args.command == "preprocess":
        cmd_preprocess(args)


if __name__ == "__main__":
    main()
