import argparse
import dataclasses as dc
import sys
from typing import cast
from unittest.mock import patch

from dopt_basics import cli

from dopt_sensor_anomalies import _interface, constants


@dc.dataclass()
class CliArgs:
    img_path: str
    calib_value_x: float
    calib_value_y: float
    anomaly_threshold: float


@patch("dopt_sensor_anomalies._find_paths.STOP_FOLDER_NAME", "src")
@patch("dopt_sensor_anomalies._find_paths.MODEL_FOLDER_NAME", "tests/_models")
def main() -> int:
    parser = argparse.ArgumentParser(
        description=("simple CLI tool to analyse single sensor images for anomalies")
    )
    parser.add_argument(
        "img_path",
        help="file path to the image which is to be analysed",
        type=str,
    )
    parser.add_argument(
        "calib_value_x",
        help="calibration value in pixels per mcm for x axis, type: float",
        type=float,
    )
    parser.add_argument(
        "calib_value_y",
        help="calibration value in pixels per mcm for y axis, type: float",
        type=float,
    )
    parser.add_argument(
        "-t",
        "--anomaly_threshold",
        help=(
            f"optional anomaly threshold to set, default: "
            f"{constants.ANOMALY_THRESHOLD_DEFAULT}, type: float"
        ),
        default=constants.ANOMALY_THRESHOLD_DEFAULT,
        type=float,
    )
    args = cast(CliArgs, parser.parse_args())

    with cli.LoadingAnimation(
        "Perform anomaly detection...",
        "Pipeline ended successfully!",
    ) as loader:
        status = _interface.sensor_anomalies_detection(
            args.img_path,
            args.calib_value_x,
            args.calib_value_y,
            args.anomaly_threshold,
        )
        if status != 0:
            loader.stop(interrupt=True)

    sys.exit(status)


if __name__ == "__main__":
    main()
