"""The video generator tool is used to generate videos from the tracking
data generated by the idtracker.ai software, see :ref:`video generator`."""

import argparse
import logging
from pathlib import Path

from idtrackerai import IdtrackeraiError, Session
from idtrackerai.utils import wrap_entrypoint

from .general_video import generate_general_video
from .individual_videos import generate_individual_video

__all__ = ["generate_general_video", "generate_individual_video"]


@wrap_entrypoint
def idtrackerai_video_entrypoint() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "session_path",
        type=Path,
        help="Path to the video session created during the tracking session",
        metavar="",
        nargs="?",
    )

    parser.add_argument(
        "--run", action="store_true", help="Generate the video without GUI"
    )

    parser.add_argument(
        "--individual",
        action="store_true",
        help="Generate individual video. Default is a general video",
    )
    parser.add_argument(
        "--gray", action="store_true", help="Draw the original video in grayscale"
    )

    parser.add_argument(
        "--t",
        type=Path,
        help=(
            "Path to the trajectory file, default is "
            "session_dir/trajectories/trajectories*"
        ),
        metavar="",
    )
    parser.add_argument(
        "--tl",
        type=int,
        default=20,
        help=(
            "Trail length, number of points used to draw the individual trajectories"
            " traces in general videos. Default is 20"
        ),
        metavar="",
    )
    parser.add_argument(
        "--s", type=int, default=0, help="Frame where to start the video", metavar=""
    )
    parser.add_argument(
        "--e", type=int, help="Frame where to end the video", metavar=""
    )
    parser.add_argument(
        "--size",
        type=int,
        help=(
            "Size of the squared individual videos. Defaults to the median body length"
            " of the animals."
        ),
        metavar="",
    )
    parser.add_argument(
        "--no-labels",
        action="store_true",
        help="Show centroids in general video without labeled ID's",
    )
    args = parser.parse_args()

    if not args.run:
        run_gui(args.session_path)
        return

    if args.session_path is None:
        raise IdtrackeraiError(
            "A session path is required when using '--run' to generate the video from the terminal."
        )

    try:
        session = Session.load(args.session_path)
    except FileNotFoundError as exc:
        raise IdtrackeraiError() from exc

    if args.no_labels:
        labels = []
    else:
        labels = session.identities_labels or list(
            map(str, range(1, session.n_animals + 1))
        )

    if args.individual:
        if args.no_labels:
            logging.info('Ignoring "--no-labels" flag')

        generate_individual_video(
            session,
            args.t,
            draw_in_gray=args.gray,
            starting_frame=args.s,
            ending_frame=args.e,
            miniframe_size=args.size,
            labels=labels,
        )
    else:
        generate_general_video(
            session,
            args.t,
            draw_in_gray=args.gray,
            centroid_trace_length=args.tl,
            starting_frame=args.s,
            ending_frame=args.e,
            labels=labels,
        )


def run_gui(session: str | Path | None = None) -> None:
    import sys

    from qtpy.QtWidgets import QApplication

    from .video_generator_gui import VideoGeneratorGUI

    app = QApplication(sys.argv)
    window = VideoGeneratorGUI()
    window.show()
    if session:
        window.open(session)
    app.exec()


if __name__ == "__main__":
    idtrackerai_video_entrypoint()
