#@ File (label="Input folder",  style="directory")                      inputDir
#@ File (label="Output folder", style="directory")                      outputDir
#@ String (label="p63+ threshold variant", choices={"T14","T1","T2","T7"}, value="T14") variant
#@ Integer (label="Segmentation channel (blue)", value=3)               segChannel
#@ Integer (label="Quantification channel (red)", value=1)              quantChannel

import os
import sys

# Same __file__ resolution as p63_Cellpose_Batch.py -- see that file for details.
try:
    _script_path = __file__
except NameError:
    import inspect as _inspect
    _script_path = _inspect.currentframe().f_code.co_filename

if os.path.isabs(_script_path):
    _here = os.path.dirname(_script_path)
else:
    from ij import IJ as _IJ
    _rel_dir = os.path.dirname(_script_path)
    _p   = _IJ.getDirectory("plugins") or ""
    _ij  = _IJ.getDirectory("imagej")  or ""
    _cwd = os.getcwd()

    _search_bases = []
    if _p:
        _search_bases.append(os.path.join(_p, "Scripts"))
        _search_bases.append(_p)
    if _ij:
        _search_bases.append(os.path.join(_ij, "plugins", "Scripts"))
        _search_bases.append(_ij)
    _search_bases.append(_cwd)
    for _sp in sys.path:
        if _sp:
            _search_bases.append(str(_sp))

    _here = None
    for _base in _search_bases:
        _c = os.path.join(_base, _rel_dir)
        if os.path.isfile(os.path.join(_c, "navigator.py")):
            _here = _c
            break

    if _here is None:
        _here = os.path.dirname(os.path.abspath(_script_path))

if _here not in sys.path:
    sys.path.insert(0, _here)
_real_here = os.path.realpath(_here)
if _real_here != _here and _real_here not in sys.path:
    sys.path.insert(0, _real_here)

from ij import IJ

import sidecar_runner
import display
import navigator


def run():
    input_path  = str(inputDir)
    output_path = str(outputDir)

    if not os.path.isdir(input_path):
        IJ.error("p63 Review", "Input folder not found:\n" + input_path)
        return
    if not os.path.isdir(output_path):
        IJ.error("p63 Review", "Output folder not found:\n" + output_path)
        return

    summary_csv = os.path.join(output_path, "summary.csv")
    cells_csv   = os.path.join(output_path, "cells.csv")
    if not os.path.isfile(summary_csv):
        IJ.error("p63 Review", "summary.csv not found in output folder.\n"
                 "Run p63 Cellpose Batch first to generate results.")
        return
    if not os.path.isfile(cells_csv):
        IJ.error("p63 Review", "cells.csv not found in output folder.\n"
                 "Run p63 Cellpose Batch first to generate results.")
        return

    IJ.log("=== p63 Review Results ===")
    IJ.log("Input:   " + input_path)
    IJ.log("Output:  " + output_path)
    IJ.log("Variant: " + str(variant))

    summary_rows = sidecar_runner.read_summary_csv(outputDir)
    cells_data   = sidecar_runner.read_cells_csv(outputDir)

    if not summary_rows:
        IJ.log("[WARN] summary.csv is empty -- nothing to display.")
        return

    cells_by_image = {}
    for row in cells_data:
        cells_by_image.setdefault(row["image"], []).append(row)

    exts = {".tif", ".tiff", ".png", ".jpg", ".jpeg"}
    image_map = {}
    for fname in os.listdir(input_path):
        base, ext = os.path.splitext(fname)
        if ext.lower() in exts:
            image_map[base] = os.path.join(input_path, fname)

    variant_str   = str(variant)
    threshold_col = variant_str.lower() + "_threshold"

    rt = display.populate_results_table(cells_data)

    navigator.show_navigator(
        summary_rows, cells_by_image, image_map, output_path,
        variant_str, threshold_col, int(segChannel), int(quantChannel), rt,
    )

    IJ.log("=== p63 Review complete ===")


run()
