
#!/usr/bin/env python3
# TP4 CLI dispatcher for IMN259 — runs tp4A … tp4E using MI_image_numpy.py
# -----------------------------------------------------------------------------
# Tasks (from the TP handout):
# - tp4A: Gradient magnitude thresholding
# - tp4B: Zero-crossing (LoG-like)
# - tp4C: Non-maximum suppression
# - tp4D: Harris corner detector
# - tp4E: K-means segmentation (grayscale)
#
# Notes:
# * Uses the same CLI philosophy and helpers as tp3.py
# * All processing is done in grayscale as required by the TP
# -----------------------------------------------------------------------------

# python tp4.py --input IMAGE.pgm [TP FLAGS] [PARAMETERS]

import os
import argparse
from MI_image_numpy import (
    LoadImage, SaveImage, PGM_RAW,
    RGBToGray, Rescale,
    NormGradientFilter, Threshold,
    ZeroCrossing, NonMaxSupp,
    HarrisCornerDetec, KMeansSegmentation,
)
# -----------------------------------------------------------------------------

import numpy as np


# ---------- helpers ----------
def ensure_outdir(path: str):
    os.makedirs(path, exist_ok=True)


def save_step(img, outdir, stem, fmt=None):
    """Save image using grayscale PGM by default."""
    actual_fmt = fmt if fmt is not None else PGM_RAW
    outpath = os.path.join(outdir, f"{stem}.pgm")
    SaveImage(img, outpath, actual_fmt)
    print(f"[save] {outpath}")

# ---------- task implementations ----------
def run_tp4A(img, outdir, threshold, sigma):
    """Gradient magnitude thresholding."""



def run_tp4B(img, outdir, threshold, sigma):
    """Zero-crossing with Laplacian and Gaussian smoothing."""


def run_tp4C(img, outdir, sigma):
    """Non-maximum suppression."""


def run_tp4D(img, outdir, halfwinsize, k):
    """Harris corner response image."""

def run_tp4E_k2_fixed(img, outdir):
    """K-means segmentation (k=2, grayscale)."""
    
def run_tp4E(img, outdir, k):
    """K-means segmentation with k clusters (grayscale)."""



# ---------- CLI ----------
def build_parser():
    p = argparse.ArgumentParser(
        description="TP4 runner (IMN259) — feature extraction & segmentation"
    )
    p.add_argument("--input", required=True, help="Input image (PGM/PPM)")
    p.add_argument("--outdir", default="./tp4_out", help="Output directory")

    # tp4A
    p.add_argument("--tp4A", action="store_true",
                   help="Run tp4A (gradient threshold)")
    p.add_argument("--threshold", type=float, default=20.0,
                   help="Threshold (tp4A / tp4B)")
    p.add_argument("--sigma", type=float, default=1.0,
                   help="Gaussian sigma")

    # tp4C
    p.add_argument("--tp4C", action="store_true",
                   help="Run tp4C (non-max suppression)")

    # tp4D
    p.add_argument("--tp4D", action="store_true",
                   help="Run tp4D (Harris detector)")
    p.add_argument("--halfwinsize", type=int, default=3,
                   help="Harris window half-size")
    p.add_argument("--k", type=float, default=0.04,
                   help="Harris parameter k")

    # tp4B / tp4E
    p.add_argument("--tp4B", action="store_true",
                   help="Run tp4B (zero-crossing)")

    p.add_argument("--tp4Ea", action="store_true",
                   help="Run tp4E (k=2-means segmentation)")    
    p.add_argument("--tp4Eb", type=int, metavar="K",
                   help="Run tp4E (k-means segmentation) with K clusters (K>=2)")

    return p


# ---------- main ----------
def main():
    args = build_parser().parse_args()
    ensure_outdir(args.outdir)

    img = LoadImage(args.input)
    save_step(img, args.outdir, "00_input")

    # Force grayscale as required by TP4
    if img['channels'] > 1:
        RGBToGray(img)
        save_step(img, args.outdir, "00a_gray")

    if args.tp4A:
        run_tp4A(img, args.outdir, args.threshold, args.sigma)

    if args.tp4B:
        run_tp4B(img, args.outdir, args.threshold, args.sigma)

    if args.tp4C:
        run_tp4C(img, args.outdir, args.sigma)

    if args.tp4D:
        run_tp4D(img, args.outdir, args.halfwinsize, args.k)

    if args.tp4Ea:
        run_tp4E_k2_fixed(img, args.outdir)
        
    if args.tp4Eb is not None:
        run_tp4E(img, args.outdir, args.tp4Eb)

    print("Done.")


if __name__ == "__main__":
    main()
