from __future__ import annotations

from .config import Settings
from .engines.base import EngineHealth, UpscaleEngine, UpscaleEngineUnavailable, UpscaleResult
from .engines.pillow_engine import PillowUpscaleEngine
from .engines.realesrgan_ncnn_engine import RealEsrganNcnnEngine
from .image_io import DownloadedImage


class UnavailableEngine(UpscaleEngine):
    def __init__(self, settings: Settings, engine_name: str) -> None:
        self.settings = settings
        self.engine_name = engine_name

    def health(self) -> EngineHealth:
        return EngineHealth(
            status="degraded",
            engine=self.engine_name,
            device=self.settings.device,
            models_loaded=False,
        )

    def upscale(self, downloaded: DownloadedImage, scale: int, mode: str, output_format: str) -> UpscaleResult:
        raise UpscaleEngineUnavailable("Upscale engine is not available. Check model files and worker installation.")


def build_upscaler(settings: Settings) -> UpscaleEngine:
    engine_name = settings.engine.strip().lower()

    if engine_name == "pillow":
        return PillowUpscaleEngine(settings)

    if engine_name in {"realesrgan", "realesrgan-ncnn"}:
        return RealEsrganNcnnEngine(settings)

    return UnavailableEngine(settings, engine_name or "unknown")