# -*- coding: utf-8 -*-
from pathlib import Path

import pytest
import responses

from arkindex import ArkindexClient
from arkindex.exceptions import SchemaError

DUMMY_SCHEMA = Path(__file__).absolute().parent / "schema.json"


def test_invalid_url():
    with pytest.raises(
        SchemaError,
        match=r"Could not retrieve a proper OpenAPI schema from http://aaa/api/v1/openapi/\?format=json",
    ):
        ArkindexClient(base_url="http://aaa")


def test_http_error():
    responses.add(
        responses.GET,
        "https://dummy.test/api/v1/openapi/?format=json",
        status=418,
    )
    with pytest.raises(SchemaError):
        ArkindexClient(base_url="https://dummy.test/")


def test_invalid_json():
    responses.add(
        responses.GET,
        "https://dummy.test/api/v1/openapi/?format=json",
        body="{",
    )
    with pytest.raises(SchemaError):
        ArkindexClient(base_url="https://dummy.test/")


def test_no_endpoints():
    responses.add(
        responses.GET,
        "https://dummy.test/api/v1/openapi/?format=json",
        json={
            "openapi": "3.0.2",
            "info": {"title": "/dev/null", "version": "0"},
            "paths": {},
        },
    )
    with pytest.raises(
        SchemaError,
        match="An OpenAPI document must contain at least one valid operation.",
    ):
        ArkindexClient(base_url="https://dummy.test/")


def test_schema_url():
    with DUMMY_SCHEMA.open() as f:
        responses.add(
            responses.GET,
            "http://dev/null",
            body=f.read(),
        )
    cli = ArkindexClient(base_url="https://dummy.test/", schema_url="http://dev/null")
    assert cli.document.url == "https://dummy.test/"
    assert list(cli.document.links.keys()) == [
        "ListElements",
        "ListProcessElements",
        "UploadDataFile",
        "ListElementMetaData",
        "Login",
    ]


def test_local_path():
    cli = ArkindexClient(base_url="https://dummy.test/", schema_url=str(DUMMY_SCHEMA))
    assert cli.document.url == "https://dummy.test/"
    assert list(cli.document.links.keys()) == [
        "ListElements",
        "ListProcessElements",
        "UploadDataFile",
        "ListElementMetaData",
        "Login",
    ]
