import sys
import os
import pytest
from flask import Flask
from flask_httpauth import HTTPBasicAuth
import base64

sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../app')))
from config import Config
from routes import setup_routes
from redis_config import setup_redis
from limiter_config import setup_limiter

auth = HTTPBasicAuth()

# Force configuration to use fallback values
class TestConfig(Config):
    SECRET_KEY = '28c93e98b2a87e47db16372bdb6e7593fb1addf9ccc10eae562827a7358cab3b'

# Adding LAPTOP_MAC environment variable
os.environ['LAPTOP_MAC'] = '00:00:00:00:00:00'

@pytest.fixture
def app():
    app = Flask(__name__)
    app.config.from_object(TestConfig)
    redis_connection = setup_redis(app)
    setup_routes(setup_limiter(app), app, redis_connection)
    return app

@pytest.fixture
def client(app):
    return app.test_client()

@pytest.fixture
def auth_headers():
    password = '4acG2wHmp1-B'
    credentials = f"anon:{password}"
    encoded_credentials = base64.b64encode(credentials.encode()).decode('utf-8')
    headers = {
        'Authorization': f'Basic {encoded_credentials}'
    }
    return headers 

def test_wol_valid_device(client, auth_headers):
    response = client.get('/wol/laptop?key=28c93e98b2a87e47db16372bdb6e7593fb1addf9ccc10eae562827a7358cab3b', headers=auth_headers)
    assert response.status_code == 200

def test_unauthorized_wol(client):
    response = client.get('/wol/device1?key=wrongkey')
    assert response.status_code == 401

def test_invalid_device(client, auth_headers):
    response = client.get('/wol/invalid_device?key=28c93e98b2a87e47db16372bdb6e7593fb1addf9ccc10eae562827a7358cab3b', headers=auth_headers)
    assert response.status_code == 400

def test_redis_status(client, auth_headers):
    response = client.get('/redis_status', headers=auth_headers)
    assert response.status_code == 200

def test_reset_limiter(client, auth_headers):
    response = client.get('/reset_limiter?key=28c93e98b2a87e47db16372bdb6e7593fb1addf9ccc10eae562827a7358cab3b', headers=auth_headers)
    assert response.status_code == 200
