"""main pipeline interface for external calls"""

from __future__ import annotations

import sys
from typing import TYPE_CHECKING, TextIO

from dopt_sensor_anomalies import detection

if TYPE_CHECKING:
    from dopt_basics.result_pattern import Status


def _print_error_state(
    state: Status,
    out_stream: TextIO,
) -> None:
    if state.ExceptionType is None:
        raise RuntimeError("Tried to treat state as error, but no exception is registered")

    msg = (
        f"During the procedure the following exception occurred:"
        f"\nType: {state.ExceptionType.__name__}\nDescription: {state.description}\n"
        f"Message: {state.message}"
    )
    print(f"\r{msg}", flush=True, file=out_stream)


def sensor_anomalies_detection(
    user_img_path: str,
    pixels_per_metric_X: float,
    pixels_per_metric_Y: float,
) -> int:
    res = detection.pipeline(
        user_img_path=user_img_path,
        pixels_per_metric_X=pixels_per_metric_X,
        pixels_per_metric_Y=pixels_per_metric_Y,
    )
    if res.status.code != 0:
        _print_error_state(res.status, out_stream=sys.stderr)
        return 1

    res.unwrap()
    return 0
