from flask import request
from .utils import load_env_config, verify_server_once
import requests

def create_before_request_handler(app):
    """
    Automatically track all routes using Flask before_request.
    """
    config = load_env_config()
    api_key = config.get("BELL_KEY")
    if not api_key:
        raise Exception("Bell Tag: BELL_KEY missing in .env")

    verify_server_once(api_key)

    @app.before_request
    def track_request():
        try:
            ip_address = request.headers.get('X-Forwarded-For', request.remote_addr)
            user_agent = request.headers.get('User-Agent')
            path = request.path
            method = request.method

            requests.post(
                "https://belltagmanager.com/api/v1/track",
                json={
                    "api_key": api_key,
                    "path": path,
                    "method": method,
                    "ip": ip_address,
                    "user_agent": user_agent
                },
                timeout=3
            )
        except Exception:
            pass  # fail silently
