"""
InsAIts SDK - Configuration
===========================
Centralized configuration for the SDK.

SIMPLIFIED TIERS (2025-02):
- FREE: Basic access with limits
- LIFETIME: Full unlimited access (contact info@yuyai.pro)

Monthly subscription tiers commented out for future reactivation.
"""

import os

# ============================================
# Development/Testing Mode
# ============================================

# Enable development mode for testing
DEV_MODE = os.getenv("INSAITS_DEV_MODE", "").lower() == "true"

# SECURITY: Test API keys moved to tests/conftest.py (never ship in production code)
# Use DEV_MODE + INSAITS_DEV_TIER env var for local testing instead
DEV_API_KEYS = {}  # Empty — populated only by test fixtures

# ============================================
# API Configuration
# ============================================

# Production API URL (Railway deployment)
API_BASE_URL = "https://insaitsapi-production.up.railway.app"
API_URL_DEV = "http://localhost:8000"

# Use dev URL if environment variable is set
if os.getenv("INSAITS_DEV_MODE"):
    API_BASE_URL = API_URL_DEV
# Allow custom API URL override
if os.getenv("INSAITS_API_URL"):
    API_BASE_URL = os.getenv("INSAITS_API_URL")

API_ENDPOINTS = {
    "validate": f"{API_BASE_URL}/api/keys/validate",
    "usage_check": f"{API_BASE_URL}/api/usage/check",
    "usage_track": f"{API_BASE_URL}/api/usage/track",
    "embeddings": f"{API_BASE_URL}/api/embeddings/generate",
    "decipher": f"{API_BASE_URL}/api/decipher/expand",
    "decipher_status": f"{API_BASE_URL}/api/decipher/status",
    "register": f"{API_BASE_URL}/api/keys/generate",
}


# ============================================
# Tier Limits
# ============================================

# Anonymous (no API key) - reasonable daily use, encourages registration
# All tiers can use InsAIts features, just with different limits
ANONYMOUS_LIMITS = {
    "session_messages": 50,   # Enough to test features
    "daily_messages": 50,     # Reasonable daily use
    "history_size": 50,
    "cloud_embeddings": False,
    "export": False,
    "show_warning": True,     # Show "register for more" warning
}

# Free tier (registered, free API key)
FREE_TIER_LIMITS = {
    "daily_messages": 100,
    "session_messages": 100,
    "history_size": 100,
    "cloud_embeddings": False,
    "export": False,
    "show_warning": False,
}

# ============================================
# SIMPLIFIED TIERS (2025-02): FREE + LIFETIME only
# Monthly subscription tiers commented out for future reactivation
# ============================================

# Lifetime tier (one-time payment, contact info@yuyai.pro)
LIFETIME_TIER_LIMITS = {
    "daily_messages": -1,  # Unlimited
    "session_messages": -1,
    "history_size": -1,
    "cloud_embeddings": True,
    "export": True,
    "show_warning": False,
}

# COMMENTED OUT: Monthly subscription tiers (reactivate in 2-3 months)
# STARTER_TIER_LIMITS = {
#     "daily_messages": 10000,
#     "session_messages": 10000,
#     "history_size": 1000,
#     "cloud_embeddings": True,
#     "export": True,
#     "show_warning": False,
# }
# PRO_TIER_LIMITS = {
#     "daily_messages": -1,  # Unlimited
#     "session_messages": -1,
#     "history_size": 10000,
#     "cloud_embeddings": True,
#     "export": True,
#     "show_warning": False,
# }

TIER_LIMITS = {
    "anonymous": ANONYMOUS_LIMITS,
    "free": FREE_TIER_LIMITS,
    # Lifetime tiers (all map to unlimited)
    "lifetime": LIFETIME_TIER_LIMITS,
    "lifetime_starter": LIFETIME_TIER_LIMITS,  # Upgraded to full lifetime
    "lifetime_pro": LIFETIME_TIER_LIMITS,
    "enterprise": LIFETIME_TIER_LIMITS,
    # Backward compatibility aliases (map to free)
    "starter": FREE_TIER_LIMITS,  # Monthly tiers disabled, fallback to free
    "pro": FREE_TIER_LIMITS,  # Monthly tiers disabled, fallback to free
}


# ============================================
# Cache Settings
# ============================================

LICENSE_CACHE_TTL = 3600  # 1 hour - how long to cache license validation
EMBEDDING_CACHE_SIZE = 2000
OFFLINE_GRACE_PERIOD = 86400  # 24 hours - allow cached validation if offline


# ============================================
# Feature Flags
# SIMPLIFIED (2025-02): FREE + LIFETIME only
# ============================================

# Anonymous (no API key) - can use all local features, no cloud
# All tiers can use InsAIts, only cloud/PRO features are limited
ANONYMOUS_FEATURES = {
    "anomaly_detection": True,
    "local_embeddings": True,
    "synthetic_embeddings": True,
    "cloud_embeddings": False,  # Cloud only for paid
    "cloud_decipher": False,    # Cloud only for paid
    "local_decipher": True,
    "conversation_reading": True,
    "export": False,            # Paid feature
    "graph": True,              # Everyone can use
    "cloud_sync": False,        # Cloud only for paid
    "dashboard": True,          # Everyone can use
    "integrations": True,       # Everyone can use
    "fact_tracking": True,      # Hallucination detection for all
    "source_grounding": True,   # Hallucination detection for all
    "self_consistency": True,   # Hallucination detection for all
}

# Free tier (registered, free API key)
FREE_FEATURES = {
    "anomaly_detection": True,
    "local_embeddings": True,
    "synthetic_embeddings": True,
    "cloud_embeddings": False,
    "cloud_decipher": True,  # 20/day limit
    "local_decipher": True,
    "conversation_reading": True,
    "export": False,
    "graph": True,
    "cloud_sync": False,
    "dashboard": True,
    "integrations": True,
    "fact_tracking": True,
    "source_grounding": True,
    "self_consistency": True,
}

# Lifetime tier (one-time payment, contact info@yuyai.pro)
LIFETIME_FEATURES = {
    "anomaly_detection": True,
    "local_embeddings": True,
    "synthetic_embeddings": True,
    "cloud_embeddings": True,
    "cloud_decipher": True,  # Unlimited
    "local_decipher": True,
    "conversation_reading": True,
    "export": True,
    "graph": True,
    "cloud_sync": True,
    "dashboard": True,
    "integrations": True,
    "fact_tracking": True,
    "source_grounding": True,
    "self_consistency": True,
}

FEATURES = {
    "anonymous": ANONYMOUS_FEATURES,
    "free": FREE_FEATURES,
    # Lifetime tiers (all have full access)
    "lifetime": LIFETIME_FEATURES,
    "lifetime_starter": LIFETIME_FEATURES,  # Upgraded to full lifetime
    "lifetime_pro": LIFETIME_FEATURES,
    "enterprise": LIFETIME_FEATURES,
    # Backward compatibility (monthly tiers disabled, map to free)
    "starter": FREE_FEATURES,
    "pro": FREE_FEATURES,
}


# ============================================
# Open-Core Feature Classification
# ============================================

# Features that require the premium package (proprietary)
PREMIUM_FEATURES = {
    "shorthand_detection",
    "context_loss_detection",
    "cross_llm_shorthand",
    "cross_llm_jargon",
    "anchor_drift",
    "anchor_suppression",
    "adaptive_dictionary",
    "domain_dictionaries",
    "dictionary_export_import",
    "auto_expand_terms",
    "decipher_full",
    "learn_from_session",
}

# Features available in open-source (no premium needed)
OPEN_FEATURES = {
    "anomaly_detection",
    "local_embeddings",
    "synthetic_embeddings",
    "conversation_reading",
    "forensic_chain_tracing",
    "hallucination_detection",
    "fact_tracking",
    "source_grounding",
    "self_consistency",
    "phantom_citation_detection",
    "confidence_decay_tracking",
    "dashboard",
    "integrations",
    "trend_analysis",
    "graph",
    "low_confidence_detection",
    "llm_fingerprint_mismatch",
}


def get_feature(tier: str, feature: str) -> bool:
    """Check if a feature is available for a tier."""
    tier_features = FEATURES.get(tier, FEATURES["anonymous"])
    return tier_features.get(feature, False)


def is_premium_feature(feature: str) -> bool:
    """Check if a feature requires the premium package."""
    return feature in PREMIUM_FEATURES


def is_open_feature(feature: str) -> bool:
    """Check if a feature is available in the open-source version."""
    return feature in OPEN_FEATURES


def get_tier_limits(tier: str) -> dict:
    """Get limits for a specific tier."""
    return TIER_LIMITS.get(tier, ANONYMOUS_LIMITS)


# ============================================
# Registration & Pricing URLs
# ============================================

REGISTER_URL = "https://github.com/Nomadu27/InsAIts.API"

# Stripe URLs
PRICING_URL = "https://buy.stripe.com/00w6oH87R77T32A96Eb3q00"
STRIPE_STARTER_LIFETIME = "https://buy.stripe.com/00w6oH87R77T32A56Eb3q00"
STRIPE_PRO_LIFETIME = "https://buy.stripe.com/3cI8wPfAjak5bz61Ecb3q04"

# Gumroad URLs (alternative payment)
GUMROAD_STARTER_LIFETIME = "https://steddy.gumroad.com/l/InsAItsStarter"
GUMROAD_PRO_LIFETIME = "https://steddy.gumroad.com/l/InsAItsPro100"


# ============================================
# Security Constants (SOC 2)
# ============================================

MAX_MESSAGE_LENGTH = 1_000_000    # 1 MB max message text
MAX_AGENT_ID_LENGTH = 255         # Max agent/sender/receiver ID length
ALLOWED_ID_PATTERN = r'^[a-zA-Z0-9_\-:.@]+$'  # Allowed chars in IDs
INSAITS_CACHE_DIR_NAME = ".insaits"
ENCRYPTION_KEY_FILENAME = ".encryption_key"
