import os
import json
import pytest
import tempfile
import importlib.util

# Import the app from the Flask app file
spec = importlib.util.spec_from_file_location("app", "/Users/wesleythijs/code/hackxpert-labs/APIs/API_basics/TheBasicsOff.py")
app_module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(app_module)
app = app_module.app

@pytest.fixture
def client():
    app.config['TESTING'] = True

    with app.test_client() as client:
        yield client

def test_help(client):
    rv = client.get('/')
    print(rv.status_code)
    print(rv.data)
    assert rv.status_code == 200
    assert b'API Help' in rv.data

def test_greet(client):
    rv = client.get('/greet?name=John')
    assert rv.status_code == 200
    assert b'Hello, John!' in rv.data

def test_math(client):
    rv = client.get('/math/2/3')
    assert rv.status_code == 200
    data = json.loads(rv.data)
    assert data['result'] == 5

def test_reverse(client):
    rv = client.post('/reverse', json={"text": "hello"})
    assert rv.status_code == 200
    data = json.loads(rv.data)
    assert data['reversed_text'] == 'olleh'

def test_dir_subdir(client):
    rv = client.get('/dir/subdir')
    assert rv.status_code == 200
    assert b'Welcome to the /dir/subdir endpoint!' in rv.data

def test_headers(client):
    rv = client.get('/headers', headers={"X-Api-Key": "12345"})
    assert rv.status_code == 200
    data = json.loads(rv.data)
    assert data['X-Api-Key'] == '12345'

def test_search(client):
    rv = client.get('/search?query=test&offset=10&limit=5')
    assert rv.status_code == 200
    data = json.loads(rv.data)
    assert len(data['results']) == 5
    assert data['offset'] == 10
    assert data['limit'] == 5

def test_upload_download(client):
    with tempfile.NamedTemporaryFile(delete=False) as temp_file:
        temp_file.write(b'Test file content')
        temp_file.flush()

        with open(temp_file.name, 'rb') as file:
            rv = client.post('/upload', data={"file": file})
            assert rv.status_code == 200
            data = json.loads(rv.data)
            uploaded_filename = data['filename']

    rv = client.get(f'sdsfsdfsdf.html')
    assert rv.status_code == 200
    assert b'Test file content' in rv.data

    os.remove(temp_file.name)
    
if __name__ == '__main__':
    pytest.main()