from pathlib import Path

from fastapi.testclient import TestClient

from app.config import Settings
from app.main import create_app


def make_settings(tmp_path: Path) -> Settings:
    return Settings(
        host="127.0.0.1",
        port=8095,
        token="secret-token",
        engine="pillow",
        device="cpu",
        max_upload_mb=20,
        max_input_width=4096,
        max_input_height=4096,
        max_output_width=8192,
        max_output_height=8192,
        tmp_dir=str(tmp_path / "tmp"),
        output_dir=str(tmp_path / "output"),
        result_ttl_minutes=60,
        model_dir=str(tmp_path / "models"),
        default_model="realesrgan-x4plus",
    )


def test_validation_rejects_invalid_scale(tmp_path: Path) -> None:
    client = TestClient(create_app(make_settings(tmp_path)))

    response = client.post(
        "/v1/upscale",
        headers={"Authorization": "Bearer secret-token"},
        json={
            "job_id": 1,
            "source_url": "https://example.com/source.webp",
            "scale": 3,
            "mode": "standard",
            "output_format": "webp",
        },
    )

    assert response.status_code == 422


def test_validation_rejects_invalid_mode(tmp_path: Path) -> None:
    client = TestClient(create_app(make_settings(tmp_path)))

    response = client.post(
        "/v1/upscale",
        headers={"Authorization": "Bearer secret-token"},
        json={
            "job_id": 1,
            "source_url": "https://example.com/source.webp",
            "scale": 2,
            "mode": "broken",
            "output_format": "webp",
        },
    )

    assert response.status_code == 422


def test_validation_rejects_invalid_output_format(tmp_path: Path) -> None:
    client = TestClient(create_app(make_settings(tmp_path)))

    response = client.post(
        "/v1/upscale",
        headers={"Authorization": "Bearer secret-token"},
        json={
            "job_id": 1,
            "source_url": "https://example.com/source.webp",
            "scale": 2,
            "mode": "standard",
            "output_format": "gif",
        },
    )

    assert response.status_code == 422


def test_validation_rejects_local_file_source_url(tmp_path: Path) -> None:
    client = TestClient(create_app(make_settings(tmp_path)))

    response = client.post(
        "/v1/upscale",
        headers={"Authorization": "Bearer secret-token"},
        json={
            "job_id": 1,
            "source_url": "file:///tmp/source.webp",
            "scale": 2,
            "mode": "standard",
            "output_format": "webp",
        },
    )

    assert response.status_code == 422