# bell_tag/decorators.py
from functools import wraps
from flask import request
import requests
from .utils import load_env_config, verify_server_once
from .exceptions import VerificationFailed

def bell_tag(name: str = None):
    """
    Decorator to track a Flask route.
    If no name is provided, use the function's __name__.
    Supports both:
        @bell_tag
        @bell_tag("custom_name")
    """
    # This inner function is the real decorator
    def decorator(f):
        route_name = name or f.__name__

        # Load API_KEY from .env
        config = load_env_config()
        api_key = config.get("BELL_KEY")
        if not api_key:
            raise VerificationFailed("Bell Tag: BELL_KEY missing in .env")

        # Perform verification once
        verify_server_once(api_key)

        @wraps(f)
        def wrapper(*args, **kwargs):
            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,
                        "route_name": route_name,
                        "path": path,
                        "method": method,
                        "ip": ip_address,
                        "user_agent": user_agent
                    },
                    timeout=3
                )
            except Exception:
                pass  # fail silently

            return f(*args, **kwargs)

        return wrapper

    # Handle the case when decorator is used without parentheses: @bell_tag
    if callable(name):
        func = name  # name is actually the function
        name = None
        return decorator(func)

    return decorator
