"""AgentBill Signals

Signal function for tracking business events and linking revenue to AI traces.
"""
import httpx
from typing import Optional, Dict, Any
from .distributed import get_trace_context


# Global configuration - set by AgentBill.init() or agentbill_tracing
_global_config: Dict[str, Any] = {}


def set_signal_config(config: Dict[str, Any]) -> None:
    """Set global configuration for signal() function."""
    global _global_config
    _global_config = config


def get_signal_config() -> Dict[str, Any]:
    """Get current global configuration."""
    return _global_config


def signal(
    event_name: str,
    revenue: Optional[float] = None,
    metadata: Optional[Dict[str, Any]] = None,
    *,
    customer_id: Optional[str] = None,
    session_id: Optional[str] = None,
    trace_id: Optional[str] = None,
    span_id: Optional[str] = None,
    currency: str = "USD",
    event_type: Optional[str] = None,
    event_value: Optional[float] = None,
) -> Dict[str, Any]:
    """
    Emit a business signal/event and link it to AI traces.
    
    This function posts to /track-ai-usage to record business events
    (conversions, purchases, signups) and link them to the AI traces
    via trace_id for revenue attribution.
    
    Args:
        event_name: Name of the business event (e.g., "purchase", "signup", "conversion")
        revenue: Revenue amount associated with this event
        metadata: Additional metadata for the event
        customer_id: Customer ID (uses global config if not provided)
        session_id: Session ID for attribution
        trace_id: Trace ID to link to (auto-detected from context if not provided)
        span_id: Span ID to link to (auto-detected from context if not provided)
        currency: Currency for revenue (default: USD)
        event_type: Type of event for categorization
        event_value: Numeric value of the event
        
    Returns:
        Dict with status and any response data
        
    Example:
        >>> # After a successful purchase
        >>> signal(
        ...     event_name="purchase",
        ...     revenue=99.99,
        ...     metadata={"product_id": "prod-123", "quantity": 1}
        ... )
        
        >>> # Track a conversion with explicit trace linking
        >>> signal(
        ...     event_name="signup_complete",
        ...     event_type="conversion",
        ...     event_value=1,
        ...     trace_id="abc123"  # Links to the AI call that led to signup
        ... )
    """
    config = get_signal_config()
    
    # Get API key from config
    api_key = config.get("api_key")
    if not api_key:
        raise ValueError("AgentBill not initialized. Call AgentBill.init() first or use agentbill_tracing context.")
    
    # Use provided customer_id or fall back to config
    effective_customer_id = customer_id or config.get("customer_id")
    
    # Auto-detect trace context if not provided
    if not trace_id or not span_id:
        ctx = get_trace_context()
        if ctx:
            trace_id = trace_id or ctx.get("trace_id")
            span_id = span_id or ctx.get("span_id")
    
    # Build the signal payload
    base_url = config.get("base_url", "https://bgwyprqxtdreuutzpbgw.supabase.co")
    url = f"{base_url}/functions/v1/track-ai-usage"
    
    payload = {
        "api_key": api_key,
        "event_name": event_name,
        "is_business_event": True,  # Flag to indicate this is a business signal, not AI usage
    }
    
    # Add optional fields
    if effective_customer_id:
        payload["customer_id"] = effective_customer_id
    
    if config.get("agent_id"):
        payload["agent_id"] = config.get("agent_id")
    
    if revenue is not None:
        payload["revenue"] = revenue
        payload["currency"] = currency
    
    if event_value is not None:
        payload["event_value"] = event_value
    
    if event_type:
        payload["event_type"] = event_type
    
    if session_id:
        payload["session_id"] = session_id
    
    # CRITICAL: Include trace_id for linking revenue to AI calls
    if trace_id:
        payload["trace_id"] = trace_id
    if span_id:
        payload["span_id"] = span_id
    
    # Add metadata
    if metadata:
        payload["metadata"] = metadata
    
    debug = config.get("debug", False)
    
    try:
        with httpx.Client(timeout=10) as client:
            response = client.post(url, json=payload)
            
            if debug:
                if response.status_code == 200:
                    print(f"[AgentBill] ✓ Signal '{event_name}' tracked")
                    if revenue:
                        print(f"[AgentBill]   Revenue: ${revenue:.2f} {currency}")
                    if trace_id:
                        print(f"[AgentBill]   Linked to trace: {trace_id}")
                else:
                    print(f"[AgentBill] ⚠️ Signal tracking failed: {response.status_code}")
            
            return {
                "success": response.status_code == 200,
                "status_code": response.status_code,
                "trace_id": trace_id,
            }
            
    except Exception as e:
        if debug:
            print(f"[AgentBill] ⚠️ Signal tracking error: {e}")
        
        return {
            "success": False,
            "error": str(e),
            "trace_id": trace_id,
        }


def track_conversion(
    event_type: str,
    event_value: float,
    *,
    currency: str = "USD",
    session_id: Optional[str] = None,
    metadata: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
    """
    Track a conversion event for revenue attribution.
    
    Convenience wrapper around signal() for conversion tracking.
    
    Args:
        event_type: Type of conversion (e.g., "purchase", "signup", "subscription")
        event_value: Value of the conversion
        currency: Currency for the value
        session_id: Session ID for attribution window
        metadata: Additional conversion metadata
        
    Returns:
        Dict with status and response data
        
    Example:
        >>> track_conversion(
        ...     event_type="purchase",
        ...     event_value=49.99,
        ...     metadata={"plan": "pro", "billing": "monthly"}
        ... )
    """
    return signal(
        event_name=f"conversion_{event_type}",
        revenue=event_value,
        event_type=event_type,
        event_value=event_value,
        currency=currency,
        session_id=session_id,
        metadata=metadata,
    )
