import sys
from pathlib import Path

import click

from readseurat._version import __version__

CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"])


@click.group(context_settings=CONTEXT_SETTINGS)
@click.version_option(__version__, "--version", "-v", message="%(version)s")
def main() -> None:
    """Readseurat package command line interface."""


@main.command()
@click.argument("input", type=click.Path(exists=True, dir_okay=False, path_type=Path))
@click.argument("output", type=click.Path(dir_okay=False, path_type=Path))
@click.option(
    "--format",
    "fmt",
    type=click.Choice(["rds", "h5seurat"], case_sensitive=False),
    default=None,
    help="Input file format. Inferred from file extension if not specified.",
)
def convert(input: Path, output: Path, fmt: str | None) -> None:
    """Convert a Seurat file (RDS or H5Seurat) to H5AD format.

    INPUT is the path to the Seurat file (.rds or .h5seurat).
    OUTPUT is the path for the resulting AnnData file (.h5ad).
    """
    from readseurat._read import read_h5seurat, read_seurat

    resolved_fmt = fmt or input.suffix.lstrip(".").lower()
    if resolved_fmt == "rds":
        click.echo(f"Reading RDS file: {input}")
        adata = read_seurat(str(input))
    elif resolved_fmt in ("h5seurat", "h5"):
        click.echo(f"Reading H5Seurat file: {input}")
        adata = read_h5seurat(str(input))
    else:
        click.echo(
            f"Cannot infer format from extension '{input.suffix}'. Use --format to specify 'rds' or 'h5seurat'.",
            err=True,
        )
        sys.exit(1)

    click.echo(f"Writing H5AD file: {output}")
    adata.write_h5ad(output)  # type: ignore[invalid-argument-type]
    click.echo("Done.")
