import os
import logging
from http.server import BaseHTTPRequestHandler, HTTPServer

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s"
)

EXPECTED_TOKEN = os.getenv("AUTH_TOKEN", "")

class AuthHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        auth = self.headers.get('Authorization')

        # Log request info
        client_ip = self.client_address[0]
        logging.info(f"Auth request from {client_ip}")

        if auth == f"Bearer {EXPECTED_TOKEN}":
            logging.info("Authentication successful")
            self.send_response(200)
        else:
            logging.warning("Authentication failed")
            self.send_response(401)
        self.end_headers()

    def log_message(self, format, *args):
        # Suppress default BaseHTTPRequestHandler logging
        return

if __name__ == '__main__':
    if not EXPECTED_TOKEN:
        logging.error("AUTH_TOKEN environment variable not set. Exiting.")
        exit(1)

    server = HTTPServer(('', 5000), AuthHandler)
    logging.info("Auth server running on port 5000...")
    server.serve_forever()
