"""Command-line interface for velocity-kit with platform-specific subcommands."""

import argparse
import sys
import logging
import os

from .platforms import pipseq, tenx

logger = logging.getLogger(__name__)


def setup_logging(verbosity: int = 1):
    """Configure logging based on verbosity level."""
    level = logging.WARNING
    if verbosity == 1:
        level = logging.INFO
    elif verbosity >= 2:
        level = logging.DEBUG

    logging.basicConfig(
        level=level,
        format="[%(asctime)s] [%(levelname)s] %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S",
    )


def main():
    """Main entry point for the velocity-kit CLI."""
    parser = argparse.ArgumentParser(
        prog="velocity-kit",
        description=(
            "A cross-platform toolkit for building RNA velocity-ready "
            "spliced/unspliced matrices from 10x Genomics, Parse Biosciences, "
            "ScaleBio, Fluent BioSciences (PIPseq), and other single-cell technologies."
        ),
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )

    parser.add_argument(
        "--version",
        action="version",
        version="%(prog)s 0.1.0",
    )

    subparsers = parser.add_subparsers(
        title="platforms",
        description="Platform-specific preparation commands",
        dest="platform",
        help="Choose a platform-specific command",
    )

    # PIPseq subcommand
    pipseq_parser = subparsers.add_parser(
        "prep-pipseq",
        help="Prepare velocity matrices from PIPseeker (Fluent BioSciences PIPseq) outputs",
        description=(
            "Build velocity-compatible spliced/unspliced matrices from two "
            "PIPseeker runs.\n\n"
            "IMPORTANT:\n"
            "  --total  must point to the run that includes introns "
            "           (total = exonic + intronic).\n"
            "  --exonic must point to the RAW/UNFILTERED exons-only run.\n"
            "           Do NOT use a filtered exonic matrix, because the\n"
            "           called-cell set may not match the total matrix."
        ),
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    pipseq.add_arguments(pipseq_parser)

    # 10x Genomics subcommand
    tenx_parser = subparsers.add_parser(
        "prep-tenx",
        help="Prepare velocity matrices from 10x Genomics CellRanger outputs",
        description=(
            "Build velocity-compatible spliced/unspliced matrices from two "
            "10x Genomics CellRanger runs.\n\n"
            "IMPORTANT:\n"
            "  --total  must point to a CellRanger run with --include-introns flag\n"
            "           (total = exonic + intronic).\n"
            "  --exonic must point to the RAW/UNFILTERED exons-only count matrix\n"
            "           (e.g., raw_feature_bc_matrix directory).\n"
            "           Do NOT use filtered_feature_bc_matrix."
        ),
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    tenx.add_arguments(tenx_parser)

    # Parse Biosciences subcommand (placeholder)
    parse_parser = subparsers.add_parser(
        "prep-parse",
        help="Prepare velocity matrices from Parse Biosciences outputs (Coming soon)",
    )
    parse_parser.add_argument("--placeholder", help="Coming soon")

    # ScaleBio subcommand (placeholder)
    scalebio_parser = subparsers.add_parser(
        "prep-scalebio",
        help="Prepare velocity matrices from ScaleBio outputs (Coming soon)",
    )
    scalebio_parser.add_argument("--placeholder", help="Coming soon")

    # scVelo Analysis subcommand
    scvelo_parser = subparsers.add_parser(
        "run-scvelo",
        help="Run scVelo analysis and generate comprehensive report from loom file",
        description=(
            "Run a complete scVelo pipeline on a loom file and generate an HTML "
            "report with QC plots, velocity analysis, and visualizations.\n\n"
            "This command requires scvelo to be installed:\n"
            "  pip install scvelo\n"
            "  # or\n"
            "  pip install velocity-kit[scvelo]"
        ),
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    scvelo_parser.add_argument(
        "loom_path",
        help="Path to input .loom file generated by prep-* commands"
    )
    scvelo_parser.add_argument(
        "-o", "--output-dir",
        default="scvelo_analysis",
        help="Output directory for plots and HTML report (default: scvelo_analysis)"
    )
    scvelo_parser.add_argument(
        "-n", "--sample-name",
        default=None,
        help="Sample name for report title (default: derived from loom filename)"
    )
    scvelo_parser.add_argument(
        "-v", "--verbose",
        action="count",
        default=1,
        help="Increase verbosity (-v for INFO, -vv for DEBUG)"
    )

    # Parse arguments
    args = parser.parse_args()

    if not args.platform:
        parser.print_help()
        sys.exit(1)

    # Setup logging
    verbosity = getattr(args, "verbose", 1)
    setup_logging(verbosity)

    # Route to platform-specific handler
    if args.platform == "prep-pipseq":
        pipseq.run(args)
    elif args.platform == "prep-tenx":
        tenx.run(args)
    elif args.platform == "prep-parse":
        logger.error("Parse Biosciences support coming soon!")
        sys.exit(1)
    elif args.platform == "prep-scalebio":
        logger.error("ScaleBio support coming soon!")
        sys.exit(1)
    elif args.platform == "run-scvelo":
        run_scvelo(args)
    else:
        parser.print_help()
        sys.exit(1)


def run_scvelo(args):
    """Run scVelo analysis and report generation with optional dependency handling."""
    try:
        from .scvelo_report import run_scvelo_and_generate_report
    except ImportError as e:
        logger.error(
            "scVelo dependencies not found. Please install with:\n"
            "  pip install scvelo scanpy\n"
            "  # or\n"
            "  pip install velocity-kit[scvelo]"
        )
        logger.debug(f"Import error: {e}")
        sys.exit(1)

    # Validate input file exists
    if not os.path.exists(args.loom_path):
        logger.error(f"Input loom file not found: {args.loom_path}")
        sys.exit(1)

    # Check if file is a .loom file
    if not args.loom_path.endswith(".loom"):
        logger.warning(
            f"Input file does not have .loom extension: {args.loom_path}"
        )

    logger.info(f"Generating scVelo analysis report for: {args.loom_path}")
    logger.info(f"Output directory: {args.output_dir}")

    try:
        report_path = run_scvelo_and_generate_report(
            loom_path=args.loom_path,
            output_dir=args.output_dir,
            sample_name=args.sample_name,
        )
        logger.info(f"✓ Analysis report successfully generated: {report_path}")
    except Exception as e:
        logger.error(f"Failed to generate analysis report: {e}")
        logger.debug("Full traceback:", exc_info=True)
        sys.exit(1)


if __name__ == "__main__":
    main()
