"""
Centralized HTTP response headers for Veena3 TTS API.

All response headers should be built using these helpers to ensure consistency.

Required headers per migration.md:
- X-Request-ID: Unique request identifier
- X-TTFB-ms: Time to first byte in milliseconds
- X-RTF: Real-time factor (generation_time / audio_duration)
- X-Model-Version: Model version string
- X-Credits-Consumed: Credits used for this request (if applicable)
- X-Remaining-Credits: User's remaining credits (if applicable)
"""

from typing import Dict, Optional, Any


def build_common_headers(
    request_id: str,
    model_version: str = "not_loaded",
) -> Dict[str, str]:
    """
    Build common headers included in all responses.
    
    Args:
        request_id: Unique request identifier
        model_version: Model version string
    
    Returns:
        Dict of common headers
    """
    return {
        "X-Request-ID": request_id,
        "X-Model-Version": model_version,
    }


def build_tts_response_headers(
    request_id: str,
    model_version: str,
    format: str,
    sample_rate: int,
    stream: bool,
    audio_bytes: int,
    audio_seconds: float,
    ttfb_ms: int,
    rtf: float,
    text_chunked: bool = False,
    sr_applied: bool = False,
    seed: Optional[int] = None,
    credits_consumed: Optional[float] = None,
    remaining_credits: Optional[float] = None,
) -> Dict[str, str]:
    """
    Build complete headers for TTS response.
    
    Args:
        request_id: Unique request identifier
        model_version: Model version string
        format: Audio format (wav, opus, mp3, etc.)
        sample_rate: Output sample rate in Hz
        stream: Whether this is a streaming response
        audio_bytes: Size of audio data in bytes
        audio_seconds: Duration of audio in seconds
        ttfb_ms: Time to first byte in milliseconds
        rtf: Real-time factor
        text_chunked: Whether text was chunked for processing
        sr_applied: Whether super-resolution was applied
        seed: Random seed if specified
        credits_consumed: Credits used (if billing enabled)
        remaining_credits: User's remaining credits (if billing enabled)
    
    Returns:
        Dict of all response headers
    """
    headers = {
        "X-Request-ID": request_id,
        "X-Model-Version": model_version,
        "X-Format": format,
        "X-Sample-Rate": str(sample_rate),
        "X-Stream": str(stream).lower(),
        "X-Audio-Bytes": str(audio_bytes),
        "X-Audio-Seconds": f"{audio_seconds:.2f}",
        "X-TTFB-ms": str(ttfb_ms),
        "X-RTF": f"{rtf:.3f}",
        "X-Text-Chunked": str(text_chunked).lower(),
        "X-SR-Applied": str(sr_applied).lower(),
    }
    
    if seed is not None:
        headers["X-Seed"] = str(seed)
    
    if credits_consumed is not None:
        headers["X-Credits-Consumed"] = f"{credits_consumed:.4f}"
    
    if remaining_credits is not None:
        headers["X-Remaining-Credits"] = f"{remaining_credits:.2f}"
    
    return headers


def build_streaming_headers(
    request_id: str,
    model_version: str,
    format: str,
    sample_rate: int,
    chunking_enabled: bool = False,
    seed: Optional[int] = None,
) -> Dict[str, str]:
    """
    Build headers for streaming response.
    
    Note: Some headers (TTFB, RTF, audio duration) cannot be known at stream start.
    These are logged but not included in HTTP headers for streaming.
    
    Args:
        request_id: Unique request identifier
        model_version: Model version string
        format: Audio format
        sample_rate: Output sample rate
        chunking_enabled: Whether text chunking is enabled
        seed: Random seed if specified
    
    Returns:
        Dict of streaming response headers
    """
    headers = {
        "X-Request-ID": request_id,
        "X-Model-Version": model_version,
        "X-Format": format,
        "X-Sample-Rate": str(sample_rate),
        "X-Stream": "true",
        "X-Chunking-Enabled": str(chunking_enabled).lower(),
        # Transfer-Encoding: chunked is set automatically by StreamingResponse
    }
    
    if seed is not None:
        headers["X-Seed"] = str(seed)
    
    return headers


def build_error_headers(
    request_id: str,
    rate_limit_headers: Optional[Dict[str, str]] = None,
) -> Dict[str, str]:
    """
    Build headers for error response.
    
    Args:
        request_id: Unique request identifier
        rate_limit_headers: Optional rate limit headers to include
    
    Returns:
        Dict of error response headers
    """
    headers = {
        "X-Request-ID": request_id,
    }
    
    if rate_limit_headers:
        headers.update(rate_limit_headers)
    
    return headers


# Header name constants for consistency
class HeaderNames:
    """Constants for header names."""
    
    REQUEST_ID = "X-Request-ID"
    MODEL_VERSION = "X-Model-Version"
    FORMAT = "X-Format"
    SAMPLE_RATE = "X-Sample-Rate"
    STREAM = "X-Stream"
    AUDIO_BYTES = "X-Audio-Bytes"
    AUDIO_SECONDS = "X-Audio-Seconds"
    TTFB_MS = "X-TTFB-ms"
    RTF = "X-RTF"
    TEXT_CHUNKED = "X-Text-Chunked"
    SR_APPLIED = "X-SR-Applied"
    SEED = "X-Seed"
    CREDITS_CONSUMED = "X-Credits-Consumed"
    REMAINING_CREDITS = "X-Remaining-Credits"
    CHUNKING_ENABLED = "X-Chunking-Enabled"
    
    # Rate limiting
    RATE_LIMIT_LIMIT = "X-RateLimit-Limit"
    RATE_LIMIT_REMAINING = "X-RateLimit-Remaining"
    RETRY_AFTER = "Retry-After"

