from pathlib import Path

import pytest

from app.config import Settings
from app.engines.base import UpscaleEngineUnavailable
from app.upscaler import build_upscaler


def test_invalid_engine_returns_degraded_health(tmp_path: Path) -> None:
    upscaler = build_upscaler(
        Settings(
            engine="broken-engine",
            token="secret-token",
            tmp_dir=str(tmp_path / "tmp"),
            output_dir=str(tmp_path / "output"),
        )
    )

    health = upscaler.health()

    assert health.status == "degraded"
    assert health.models_loaded is False


def test_missing_model_raises_safe_error_when_fallback_disabled(tmp_path: Path) -> None:
    binary = tmp_path / "bin" / "realesrgan-ncnn-vulkan"
    binary.parent.mkdir(parents=True)
    binary.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")
    binary.chmod(0o755)

    model_dir = tmp_path / "models"
    model_dir.mkdir(parents=True)
    (model_dir / "realesrgan-x4plus.param").write_text("param", encoding="utf-8")
    (model_dir / "realesrgan-x4plus.bin").write_text("bin", encoding="utf-8")

    engine = build_upscaler(
        Settings(
            engine="realesrgan-ncnn",
            token="secret-token",
            tmp_dir=str(tmp_path / "tmp"),
            output_dir=str(tmp_path / "output"),
            realesrgan_bin=str(binary),
            realesrgan_model_dir=str(model_dir),
            realesrgan_allow_model_fallback=False,
        )
    )

    with pytest.raises(UpscaleEngineUnavailable, match="Upscale engine is not available"):
        engine.resolve_model("illustration")