# Based on the SoFT basic tracking example by Michele Berretti and contributors.
# Source: https://github.com/mib-unitn/SoFT/blob/4de0a50844a655f427a7f9791e12ce32c953e6c4/examples/plot_basic_usage.py
# Original copyright and GPLv3 terms apply; see GPL-3.0.txt.
"""Detect and track a moving feature using WaLSAlib.SoFT."""

import numpy as np
import matplotlib.pyplot as plt
from WaLSAlib import SoFT
import os
import shutil
import astropy.io.fits



def main():
    # Create a temporary directory for data
    data_dir = "temp_data" + os.sep
    os.makedirs(data_dir, exist_ok=True)
    os.makedirs(os.path.join(data_dir, "00-data"), exist_ok=True)
    os.makedirs(os.path.join(data_dir, "01-mask"), exist_ok=True)
    os.makedirs(os.path.join(data_dir, "02-id"), exist_ok=True)
    os.makedirs(os.path.join(data_dir, "03-assoc"), exist_ok=True)


    # Generate synthetic frames
    # We'll create a moving Gaussian blob
    nx, ny = 100, 100
    n_frames = 5
    x, y = np.meshgrid(np.arange(nx), np.arange(ny))

    for t in range(n_frames):
        # Blob moves along x=y
        cx, cy = 20 + t * 5, 20 + t * 5
        sigma = 5
        blob = 100 * np.exp(-((x - cx)**2 + (y - cy)**2) / (2 * sigma**2))

        # Add some noise
        noise = np.random.normal(0, 5, (ny, nx))
        frame = blob + noise

        filename = os.path.join(data_dir, "00-data", f"{t:04d}.fits")
        astropy.io.fits.writeto(filename, frame, overwrite=True)

        # Plot the first and last frame for visualization
        if t == 0 or t == n_frames - 1:
            plt.figure()
            plt.title(f"Frame {t}")
            plt.imshow(frame, origin='lower', cmap='gray')
            plt.colorbar()
            plt.show()

    # Set tracking parameters
    l_thr = 20  # Low threshold
    min_size = 10
    dx = 1.0
    dt = 1.0
    sign = "both"
    separation = True
    verbose = True
    cores = 1

    # Run tracking
    print("Running tracking...")
    SoFT.track_all(data_dir, cores, l_thr, min_size, dx, dt, sign, separation, verbose)

    # Check results
    # Read the resulting dataframe
    import pandas as pd
    df_path = os.path.join(data_dir, "dataframe.json")
    if os.path.exists(df_path):
        df = pd.read_json(df_path)
        print("Tracking results:")
        print(df.head())

        # Plot trajectory
        plt.figure()
        plt.title("Tracked Trajectory")
        for _, row in df.iterrows():
            plt.plot(row['X'], row['Y'], 'o-', label=f"Label {row['label']}")
        plt.legend()
        plt.xlabel("X pixel")
        plt.ylabel("Y pixel")
        plt.show()

    else:
        print("No dataframe found.")

    # Cleanup
    # shutil.rmtree(data_dir)


if __name__ == "__main__":
    main()
