# -*- coding: utf-8 -*-
"""
SOS (Stochastic Outlier Selection) wrapper.

Provides PyOD's SOS detector via the unified `pyimgano` vision API.
"""

from __future__ import annotations

import logging

from .baseml import BaseVisionDetector
from .registry import register_model

logger = logging.getLogger(__name__)

try:
    from pyod.models.sos import SOS as _PyODSOS

    _PYOD_AVAILABLE = True
    _IMPORT_ERROR = None
except ImportError as exc:
    _PyODSOS = None
    _PYOD_AVAILABLE = False
    _IMPORT_ERROR = exc


@register_model(
    "vision_sos",
    tags=("vision", "classical", "sos", "probabilistic", "baseline"),
    metadata={
        "description": "Stochastic Outlier Selection via PyOD (probabilistic baseline)",
        "type": "probabilistic",
    },
)
class VisionSOS(BaseVisionDetector):
    """Vision-compatible SOS detector (PyOD SOS)."""

    def __init__(
        self,
        *,
        feature_extractor=None,
        contamination: float = 0.1,
        perplexity: float = 4.5,
        metric: str = "euclidean",
        eps: float = 1e-5,
    ) -> None:
        if not _PYOD_AVAILABLE:
            raise ImportError(
                "PyOD is not available. Install it with:\n"
                "  pip install 'pyod>=1.1.0'\n"
                f"Original error: {_IMPORT_ERROR}"
            )

        if not 0 < float(contamination) < 0.5:
            raise ValueError(
                f"contamination must be in (0, 0.5), got {contamination}"
            )

        self._detector_kwargs = {
            "contamination": float(contamination),
            "perplexity": float(perplexity),
            "metric": str(metric),
            "eps": float(eps),
        }

        logger.debug("Initializing VisionSOS with kwargs=%s", self._detector_kwargs)
        super().__init__(contamination=contamination, feature_extractor=feature_extractor)

    def _build_detector(self):
        return _PyODSOS(**self._detector_kwargs)

