import arklog
from pathlib import Path

import requests
from fastapi.testclient import TestClient
from mocka.main import get_application
from mocka.configuration import Configuration, Server
from mocka.artefact import Artefact

client = TestClient(get_application(Configuration(Server("localhost", 8585))))


def test_post_octiva():
    # NOTE Needs the backend to be running to work... :(
    image_file_path = Path("octiva/rails_0.jpg")
    image_file_uri = f"http://localhost:5000/files/file/{image_file_path.name}"

    # Send the file to the endpoint as it might not be there yet.
    full_image_file_path = Path(__file__).parent / Path("octiva/rails_0.jpg")
    r = requests.put(f"http://localhost:5000/files/file/{image_file_path.name}", data=full_image_file_path.read_bytes())
    arklog.debug(r.status_code)

    image_artefact = Artefact("reference", image_file_uri, image_file_path.name, "image/jpg")
    algo_artefact = Artefact("inline", f"print('hello')", "algorithm.py", "text/plain")
    mock_input = {
        "ctrl": "cin",
        "input": {
            "image": image_artefact.as_dict(),
            "algorithm": algo_artefact.as_dict(),
        }
    }
    try:
        response = client.post("/octiva/", json=mock_input)
    except ConnectionError as e:
        raise RuntimeError(f"{e} Please run the DTD backend when doing these tests.")
    assert response.status_code == 200
    annotated_image_artefact = Artefact("reference", f"http://localhost:5000/files/file/rail_image_annotated.jpg", "rail_image_annotated.jpg", "image/jpg")
    expected_data_content =  "D: [[[108 847 108   0]]\n\n [[477 847 477   0]]]\nP: [0, 1]"
    data_artefact = Artefact("inline", expected_data_content, "rail_image_annotated.txt", "text/plain")
    assert response.json() ==  {
        "ctrl": "ok",
        "output": {
            "image": annotated_image_artefact.as_dict(),
            "data": data_artefact.as_dict(),
        }
    }
