"""Centralized constants for Maya Pipecat Application."""

import os
from dotenv import load_dotenv

load_dotenv(override=True)

APP_VERSION = os.getenv("APP_VERSION", "1.0.0")
ENVIRONMENT = os.getenv("ENVIRONMENT", "development")

# ============================================================
# FEATURE TOGGLES
# ============================================================
# Set to True to give unlimited image generation to ALL users
# Set to False to enable regular limits (premium users get unlimited, others get limited)
UNLIMITED_FOR_ALL = True  # Toggle this to enable/disable unlimited for everyone
# ============================================================

SAMPLE_RATE = 24000
SAMPLE_RATE_16K = 16000
CHUNK_DURATION = 30

NO_USER_TIMEOUT = 240
ROOM_EXPIRY_TIME = 6000

AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY")
AWS_DEFAULT_REGION = os.getenv("AWS_DEFAULT_REGION", "ap-south-1")
S3_BUCKET_NAME = os.getenv("S3_BUCKET_NAME", "agentsessiondata")
CLOUDFRONT_DOMAIN = os.getenv("CLOUDFRONT_DOMAIN", "d3mjt969vdk0bb.cloudfront.net")

# GCP Cloud Storage (replaces S3)
GCS_BUCKET_NAME = os.getenv("GCS_BUCKET_NAME", "maya-session-data")

TURSO_DATABASE_URL = os.getenv("TURSO_DATABASE_URL")
TURSO_AUTH_TOKEN = os.getenv("TURSO_AUTH_TOKEN")

# Redis Cache (ElastiCache)
REDIS_URL = os.getenv("REDIS_URL", "")  # e.g. redis://maya-redis.xxxxx.aps1.cache.amazonaws.com:6379/0
REDIS_ENABLED = os.getenv("REDIS_ENABLED", "false").lower() == "true"
REDIS_CONNECT_TIMEOUT = 3
REDIS_SOCKET_TIMEOUT = 2
REDIS_MAX_CONNECTIONS = 20
REDIS_DEFAULT_TTL = 300  # 5 minutes default TTL
REDIS_KEY_PREFIX = "maya:"  # Namespace prefix for all keys

DAILY_API_KEY = os.getenv("DAILY_API_KEY")
MAX_ROOM_PARTICIPANTS = 2

OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
AZURE_OPENAI_ENDPOINT = os.getenv(
    "AZURE_OPENAI_ENDPOINT",
    "https://bhara-mjp8hlry-eastus2.openai.azure.com/openai/v1/"
)
AZURE_OPENAI_API_KEY = os.getenv("AZURE_OPENAI_API_KEY", "43YVGjOlFLtokZ3uNzE7wV7XAPceLpUFNAeprJkpddIfgEw7y5hQJQQJ99BLACHYHv6XJ3w3AAAAACOGd0ll")
AZURE_OPENAI_DEPLOYMENT_NAME = os.getenv("AZURE_OPENAI_DEPLOYMENT_NAME", "gpt-image-1.5-2")

# Azure OpenAI STT Configuration
# NOTE: Azure requires deployment name in URL path + api-version
AZURE_STT_ENDPOINT = os.getenv(
    "AZURE_STT_ENDPOINT",
    "https://bhara-mjp8hlry-eastus2.cognitiveservices.azure.com"
)
AZURE_STT_API_KEY = os.getenv("AZURE_STT_API_KEY", "43YVGjOlFLtokZ3uNzE7wV7XAPceLpUFNAeprJkpddIfgEw7y5hQJQQJ99BLACHYHv6XJ3w3AAAAACOGd0ll")
# NOTE: For Azure, this should match the deployment name in the URL
AZURE_STT_MODEL = os.getenv("AZURE_STT_MODEL", "gpt-4o-mini-transcribe")

# Deepgram STT Configuration
DEEPGRAM_API_KEY = os.getenv("DEEPGRAM_API_KEY", "5017cf6d1803c2bec2b9d80bd3f6cca5cb32525a")

# Mistral STT Configuration (Voxtral via vLLM on Modal)
# Uses vLLM /v1/realtime WebSocket endpoint
MISTRAL_API_KEY = os.getenv("MISTRAL_API_KEY")
VOXTRAL_WS_URL = os.getenv("VOXTRAL_WS_URL", "wss://mayaresearch--voxtral-realtime-serve.modal.run/v1/realtime")
VOXTRAL_MODEL = os.getenv("VOXTRAL_MODEL", "mistralai/Voxtral-Mini-4B-Realtime-2602")

# Replicate API Configuration (for video generation)
REPLICATE_API_TOKEN = os.getenv("REPLICATE_API_TOKEN", "r8_cbBQmZcUUVbuPI8cCygelxB0mS9p2Bm1mlIdk")
REPLICATE_VIDEO_MODEL = "wan-video/wan-2.2-t2v-fast"  # Text-to-Video
REPLICATE_I2V_MODEL = "wan-video/wan-2.2-i2v-fast"    # Image-to-Video

EXTERNAL_IMAGE_EDIT_SERVICE_URL = os.getenv("EXTERNAL_IMAGE_EDIT_SERVICE_URL", "http://154.54.100.103:8080/generate_base64")

# OpenRouter Configuration (for prompt writing)
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY", "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")
OPENROUTER_PROMPT_MODEL = os.getenv("OPENROUTER_PROMPT_MODEL", "openai/gpt-4o-mini")  # Fast & cheap for prompt writing
DEFAULT_IMAGE_PROMPT_TEMPLATE = """You are an expert image prompt engineer. Transform user edit requests into detailed image editing prompts. Output ONLY the prompt, nothing else."""

GOOGLE_CLOUD_PROJECT = os.getenv("GOOGLE_CLOUD_PROJECT", "mayaresearchgcp")
GOOGLE_CLOUD_LOCATION = "asia-south1"
GCP_CREDENTIALS_PATH = "gcp-service-account.json"
GEMINI_MODEL = "gemini-2.5-flash"

# Groq LLM Configuration
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
GROQ_MODEL = os.getenv("GROQ_MODEL", "openai/gpt-oss-20b")

# OpenRouter LLM Configuration (for main LLM provider, separate from prompt-writing)
OPENROUTER_LLM_MODEL = os.getenv("OPENROUTER_LLM_MODEL", "openai/gpt-oss-20b")

TTS_API_URL = os.getenv(
    "TTS_API_URL",
    "https://mayaresearch--veena3-tts-v3-ttsservice-serve.modal.run/v1/tts/generate"
)
VEENA3_API_KEY = os.getenv("VEENA3_API_KEY")
DEFAULT_TTS_SPEAKER = "Nilay"

LLM_MAX_OUTPUT_TOKENS = 512
LLM_TEMPERATURE = 0.7
STT_MODEL = "gpt-4o-mini-transcribe-2025-12-15"
STT_LANGUAGE = "hi"

DEFAULT_IMAGE_SIZE = "1024x1024"
IMAGE_QUALITY = "low"
IMAGE_SIZE_MAP = {
    "1:1": "1024x1024",
    "16:9": "1536x1024",
    "9:16": "1024x1536",
    "4:3": "1536x1024",
    "3:4": "1024x1536",
}

DEFAULT_IMAGES_LIMIT = 20
DEFAULT_SHOWCASE_PRICE = 99900
DEFAULT_DAYS_BETWEEN_REVIEWS = 7
DEFAULT_SESSIONS_REQUIRED = 5
DEFAULT_GENERATIONS_REQUIRED = 10

# Characters cache configuration
CHARACTERS_CACHE_TTL_SECONDS = 300  # 5 minutes cache for character data

SERVER_HOST = "0.0.0.0"
SERVER_PORT = 3006

LOG_DIR = "logs"
LOG_FILE_PATH = "logs/maya.log"
LOG_ROTATION_SIZE = "100 MB"
LOG_RETENTION = "10 days"

ANDROID_PACKAGE_NAME = os.getenv("ANDROID_PACKAGE_NAME", "com.india.mayaai")

TURSO_CONNECT_TIMEOUT = 10
TURSO_READ_TIMEOUT = 30
HTTP_POOL_CONNECTIONS = 5
HTTP_POOL_MAXSIZE = 10

VAD_CONFIDENCE = 0.7
VAD_STOP_SECS = 0.8
VAD_START_SECS = 0.2
VAD_MIN_VOLUME = 0.6

STT_PROMPT = "User Talks in Hindi."

DEFAULT_SYSTEM_PROMPT = """You are Maya Global Agent, a conversational AI assistant with creative capabilities. 
You can help users generate images through function calling."""

ERROR_IMAGE_LIMIT_EXCEEDED = "अभी के लिए आप और images नहीं बना सकते क्योंकि 3 घंटे की limit window पूरी हो गई है। थोड़ा समय बाद जब यह 3 घंटे वाली window reset हो जाएगी तब आप फिर से images बना सकते हैं। तब तक अगर आप chitchat करना चाहते हैं या किसी और चीज़ में मदद चाहिए तो मैं यहाँ हूँ।"
ERROR_EDIT_LIMIT_EXCEEDED = "अभी के लिए आप और images edit नहीं कर सकते क्योंकि 3 घंटे की limit window पूरी हो गई है। थोड़ा समय बाद जब यह 3 घंटे वाली window reset हो जाएगी तब आप फिर से images edit कर सकते हैं। तब तक अगर आप chitchat करना चाहते हैं या किसी और चीज़ में मदद चाहिए तो मैं यहाँ हूँ।"
ERROR_NO_IMAGE_FOR_EDIT = "कोई image नहीं मिली। पहले image बनाओ या upload करो, फिर edit करूंगी।"
ERROR_NO_EDIT_INSTRUCTION = "क्या edit करना है? मुझे बताओ।"
ERROR_IMAGE_GENERATE_FAILED = "Image generate नहीं हो सकी।"
ERROR_IMAGE_EDIT_FAILED = "Image edit नहीं हो सकी।"
ERROR_SERVER_BUSY = "Server busy है। थोड़ी देर में try करो।"
ERROR_SERVICE_BUSY = "Image generation service is temporarily busy. Please try again in a moment."
ERROR_EDIT_SERVICE_BUSY = "Image editing service is temporarily busy. Please try again in a moment."
ERROR_TIMEOUT = "Image generation took too long. Please try a simpler request."
ERROR_GENERIC = "Unable to generate image at the moment. Please try again."
ERROR_EDIT_GENERIC = "Image edit करने में problem हुई। Please try again।"

LLM_CONTEXT_LIMIT_REFERRAL = "User has reached their image generation limit. A referral popup is being shown to them. Tell them warmly in Hindi that their image limit is reached for now, but they can get FREE bonus images by sharing Maya with their friends! When their friends install the app using their referral link, they will earn extra images. Encourage them to share with friends to unlock more images. Don't mention specific numbers. Be excited and positive about the referral opportunity!"
LLM_CONTEXT_LIMIT_SUBSCRIPTION = "User has reached their image generation limit. A subscription popup is being shown to them. Tell them warmly in Hindi that their free image limit is reached for now, but they can unlock unlimited images by subscribing to Maya Premium! With subscription they get unlimited image generation, priority processing, and exclusive features. Encourage them to check out the subscription options shown on their screen. Be enthusiastic about the premium benefits!"
LLM_CONTEXT_LIMIT_DEFAULT = "User is trying to generate an image, but they have reached the current image limit window (3 hours). Tell them politely in Hindi that right now they cannot generate more images, they can try again after some time when the limit window resets, and until then you are available to chit-chat or help with anything else."
LLM_CONTEXT_EDIT_LIMIT_REFERRAL = "User has reached their image edit limit. A referral popup is being shown to them. Tell them warmly in Hindi that their image limit is reached for now, but they can get FREE bonus images by sharing Maya with their friends! When their friends install the app using their referral link, they will earn extra images. Encourage them to share with friends to unlock more images. Don't mention specific numbers. Be excited and positive about the referral opportunity!"
LLM_CONTEXT_EDIT_LIMIT_SUBSCRIPTION = "User has reached their image edit limit. A subscription popup is being shown to them. Tell them warmly in Hindi that their free image limit is reached for now, but they can unlock unlimited images by subscribing to Maya Premium! With subscription they get unlimited image generation, priority processing, and exclusive features. Encourage them to check out the subscription options shown on their screen. Be enthusiastic about the premium benefits!"
LLM_CONTEXT_EDIT_LIMIT_DEFAULT = "User is trying to edit an image, but they have reached the current image edit limit window (3 hours). Tell them politely in Hindi that right now they cannot edit more images, they can try again after some time when the limit window resets, and until then you are available to chit-chat or help with anything else."
LLM_CONTEXT_MODERATION_BLOCKED_IMAGE = "The user's image generation request was blocked by our content moderation system. The description may have contained inappropriate content. Politely explain to the user in Hindi that their image request could not be processed because it contains content that is not allowed on our platform. Suggest they try a different description or modify their request. Be gentle and helpful, don't shame them."
LLM_CONTEXT_MODERATION_BLOCKED_EDIT = "The user's image edit request was blocked by our content moderation system. The image or edit instruction may have contained inappropriate content. Politely explain to the user in Hindi that their image edit request could not be processed because it contains content that is not allowed on our platform. Suggest they try a different image or modify their edit request. Be gentle and helpful, don't shame them."
LLM_CONTEXT_RATE_LIMIT = "The image generation service is currently busy. Politely explain in Hindi that the service is temporarily unavailable due to high demand, and ask them to wait a moment before trying again. Be friendly and apologetic. Don't mention rate limits or technical details. Just say the service is busy and suggest trying again in a few seconds or minutes."

IMAGE_PROMPT_INDIAN_SUFFIX = " with vibrant Indian-inspired detailing"
IMAGE_PROMPT_FRAMING = ". Full frame composition, no cropping, entire subject visible within the image boundaries (aspect ratio {aspect_ratio})"

EDIT_PROMPT_TEMPLATE = "{edit_instruction}. Style: {style}. Keep the subject and composition similar, just apply the requested changes. Make it look natural and high quality."
EDIT_NEGATIVE_PROMPT = "changing facial features, altering face structure, different face shape, modified facial identity, changed skin tone, blurry, low quality, distorted face, deformed, bad anatomy, wrong proportions, extra limbs, disfigured, mutated hands, poorly drawn face, mutation, extra fingers, fewer fingers, cropped, worst quality, jpeg artifacts, inconsistent lighting, mismatched background, different lighting on subjects, inconsistent shadows, inconsistent color temperature, mismatched atmosphere, different moods, clashing vibes, weird composition, unnatural pose, awkward positioning, different environments for each subject, artificial appearance, visible cutouts, poorly blended edges, mismatched perspectives, different time of day, inconsistent weather conditions, conflicting styles"

IMAGE_LOADER_TIME_SECONDS = 25
