import ghttp
import base64

def wrapper(serv, addr):
    question, data, headers = serv.read()
    
    # Проверяем Authorization
    auth = headers.get('authorization')
    
    if auth and auth.startswith('Basic '):
        try:
            creds = base64.b64decode(auth[6:]).decode('utf-8')
            login, password = creds.split(':', 1)
            print(f"Login: {login}, Password: {password}")
            
            if login == 'auth' and password == '123':
                serv.send(b'<h1>Welcome! You are authenticated!</h1>')
                print("Sended 200")
                return
            else:
                serv.send(b'<h1>Invalid credentials!</h1>', status_code='401 Unauthorized')
                print("Sended 401")
                return
        except:
            serv.send(b'<h1>Invalid auth format!</h1>', status_code='400 Bad Request')
            print("Sended 400")
            return
    
    # Если нет Authorization - требуем аутентификацию
    serv.send(
        b'<h1>Authentication required</h1>', 
        status_code='401 Unauthorized',
        headers={'WWW-Authenticate': 'Basic realm="Protected Area"'}
    )
    print("Sended 401 with WWW-Authenticate")

ghttp.server(wrapper)