# Updated cli.py with enhanced help text for each command and option
import click
from .combine import combine_channels
from .segment import segment_images
from .measure import measure_intensities
from .quantify import quantify_cells
from .visualize import launch_viewer
import os

@click.group()
@click.version_option(version='0.1', prog_name='twotuft2count')
def main():
    """twotuft2count CLI: Process, analyze, and visualize multiplexed imaging data."""
    pass

@main.command()
@click.argument('input_dir')
@click.argument('output_dir')
def combine(input_dir, output_dir):
    """Combine single-channel TIFFs into multi-channel TIFFs based on filename index.

    Expects files like 'sample_ch0.tif', 'sample_ch1.tif'. Channels are stacked by index.
    """
    combine_channels(input_dir, output_dir)

@main.command()
@click.argument('input_dir')
@click.argument('output_dir')
def segment(input_dir, output_dir):
    """Run segmentation (InstanSeg) on multi-channel TIFFs.

    Uses pretrained models to segment cells or nuclei. Saves output masks to output_dir.
    """
    segment_images(input_dir, output_dir)

@main.command()
@click.argument('image_dir')
@click.argument('mask_dir')
@click.option('--csv-dir', default='csv', show_default=True,
              help='Folder to save per-image CSVs with per-cell intensities and morphology.')
@click.option('--fcs-dir', default='fcs', show_default=True,
              help='Folder to save per-image FCS files compatible with FlowJo/CytoBank.')
@click.option('--combined-fcs', default='all_images_fcs/combined.fcs', show_default=True,
              help='Path to save merged FCS file containing all images.')
@click.option('--panel', default='panel.csv', show_default=True,
              help="CSV with 'channel' and 'marker' columns to map image channels to marker names.")
def measure(image_dir, mask_dir, csv_dir, fcs_dir, combined_fcs, panel):
    """Measure per-cell intensities for all image/mask pairs and export CSV + FCS files."""
    measure_intensities(image_dir, mask_dir, csv_dir, fcs_dir, combined_fcs, panel)

@main.command()
@click.option('--csv-dir', default='csv', show_default=True,
              help="Directory containing per-cell CSVs generated by the measure step.")
@click.option('--results-dir', default='results', show_default=True,
              help="Directory to save marker quantification summaries per image.")
@click.option('--panel', default='panel.csv', show_default=True,
              help="CSV with 'channel' and 'marker' columns defining channel order and marker names.")
@click.option('--use-manual-thresholds', is_flag=True, show_default=True,
              help="Use thresholds from a *_thresholds.json file rather than computing from data.")
@click.option('--threshold-source-image', default=None,
              help="Image base name used to locate *_thresholds.json (e.g., 'sample1'). If omitted, the first threshold file found in csv-dir is used.")
def quantify(csv_dir, results_dir, panel, use_manual_thresholds, threshold_source_image):
    """Quantify marker-positive populations based on thresholds and DAPI gating."""
    quantify_cells(
        csv_dir=csv_dir,
        results_dir=results_dir,
        panel=panel,
        use_manual_thresholds=use_manual_thresholds,
        threshold_source_image=threshold_source_image
    )

@main.command()
@click.argument('image_base')
@click.option('--img-dir', default='img', show_default=True,
              help="Directory containing multi-channel TIFF images (e.g., sample1.tiff).")
@click.option('--mask-dir', default='masks', show_default=True,
              help="Directory containing mask label TIFFs matching image base names.")
@click.option('--csv-dir', default='csv', show_default=True,
              help="Directory containing per-cell measurement CSVs.")
@click.option('--panel', default='panel.csv', show_default=True,
              help="Path to panel.csv with 'channel' and 'marker' columns to map channels to markers.")
@click.option('--threshold-json-out', default=None,
              help="Optional path to save threshold values set in the GUI to a *_thresholds.json file.")
@click.option('--use-manual-thresholds', is_flag=True,
              help="Load thresholds from a *_thresholds.json file rather than computing anew.")
@click.option('--threshold-source-image', default=None,
              help="Base name of image to use for loading *_thresholds.json (e.g., 'sample1').")
def visualize(image_base, img_dir, mask_dir, csv_dir, panel,
              threshold_json_out, use_manual_thresholds, threshold_source_image):
    """Launch Napari GUI for interactive threshold tuning and cell identity visualization."""
    image_path = os.path.join(img_dir, f"{image_base}.tiff")
    label_path = os.path.join(mask_dir, f"{image_base}.tiff")
    csv_path = os.path.join(csv_dir, f"{image_base}.csv")

    if threshold_json_out is None:
        threshold_json_out = os.path.join(csv_dir, f"{image_base}_thresholds.json")

    launch_viewer(image_path, label_path, csv_path, panel,
                  threshold_json_out=threshold_json_out,
                  use_manual_thresholds=use_manual_thresholds,
                  threshold_source_image=threshold_source_image)
