"""
Gift-Advisor SaaS 配置管理
"""
import os
from typing import List, Optional
from pydantic_settings import BaseSettings
from pydantic import validator

class Settings(BaseSettings):
    """应用配置"""
    
    # 应用基本信息
    APP_NAME: str = "Gift-Advisor SaaS"
    APP_VERSION: str = "2.0.0"
    API_PREFIX: str = "/api/v1"
    
    # 服务器配置
    HOST: str = "0.0.0.0"
    PORT: int = 8000
    DEBUG: bool = False
    LOG_LEVEL: str = "INFO"
    
    # 数据库配置
    DATABASE_URL: str = "postgresql://giftadmin:giftpass123@localhost:5432/gift_advisor"
    
    # Redis配置
    REDIS_URL: str = "redis://localhost:6379"
    REDIS_CACHE_TTL: int = 300  # 5分钟
    
    # JWT配置
    JWT_SECRET_KEY: str = "your-jwt-secret-key-change-in-production"
    JWT_ALGORITHM: str = "HS256"
    JWT_ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 7  # 7天
    
    # API密钥配置
    API_KEY_HEADER: str = "X-API-Key"
    API_KEY_LENGTH: int = 64
    
    # CORS配置
    ALLOWED_ORIGINS: List[str] = [
        "http://localhost:3000",
        "http://localhost:8080",
        "https://gift-advisor.com",
        "https://www.gift-advisor.com"
    ]
    
    # 订阅计划配置
    SUBSCRIPTION_PLANS: dict = {
        "free": {
            "name": "免费版",
            "price": 0,
            "features": ["基础推荐", "20+禁忌过滤", "个性化祝福语", "对话式推荐"],
            "limits": {
                "daily_calls": 100,
                "monthly_calls": 3000,
                "concurrent_calls": 1,
                "api_keys": 1
            }
        },
        "personal": {
            "name": "个人专业版",
            "price": 9.9,  # USD/月
            "features": [
                "所有基础功能",
                "电商购物链接",
                "用户记忆银行",
                "场景模拟",
                "24小时技术支持"
            ],
            "limits": {
                "daily_calls": 1000,
                "monthly_calls": 30000,
                "concurrent_calls": 5,
                "api_keys": 3
            }
        },
        "business": {
            "name": "企业高级版",
            "price": 49,  # USD/月
            "features": [
                "所有个人版功能",
                "企业级API",
                "定制推荐算法",
                "数据分析报表",
                "私有化部署支持",
                "专属客户经理"
            ],
            "limits": {
                "daily_calls": 10000,
                "monthly_calls": 300000,
                "concurrent_calls": 50,
                "api_keys": 20
            }
        }
    }
    
    # 电商API配置
    ECOMMERCE_PLATFORMS: dict = {
        "jd": {
            "name": "京东联盟",
            "api_url": "https://api.jd.com/routerjson",
            "app_key": "",
            "app_secret": "",
            "commission_rate": 0.10,  # 10%佣金
            "enabled": False
        },
        "taobao": {
            "name": "淘宝客",
            "api_url": "https://eco.taobao.com/router/rest",
            "app_key": "",
            "app_secret": "",
            "commission_rate": 0.08,  # 8%佣金
            "enabled": False
        }
    }
    
    # 支付网关配置
    PAYMENT_GATEWAYS: dict = {
        "stripe": {
            "enabled": True,
            "public_key": "",
            "secret_key": "",
            "webhook_secret": ""
        },
        "alipay": {
            "enabled": True,
            "app_id": "",
            "merchant_private_key": "",
            "alipay_public_key": "",
            "notify_url": ""
        },
        "wechat_pay": {
            "enabled": True,
            "app_id": "",
            "merchant_id": "",
            "merchant_key": "",
            "notify_url": ""
        }
    }
    
    # 监控和告警配置
    MONITORING: dict = {
        "prometheus_enabled": True,
        "grafana_enabled": True,
        "alert_rules": {
            "error_rate_threshold": 0.01,  # 1%
            "response_time_threshold": 0.5,  # 500ms
            "database_connection_threshold": 0.8  # 80%
        }
    }
    
    # 安全配置
    SECURITY: dict = {
        "rate_limit_enabled": True,
        "rate_limit_per_minute": 60,
        "rate_limit_per_hour": 1000,
        "rate_limit_per_day": 10000,
        "password_min_length": 8,
        "password_require_numbers": True,
        "password_require_special_chars": True,
        "session_timeout_minutes": 30
    }
    
    # 邮件配置
    EMAIL: dict = {
        "enabled": True,
        "smtp_server": "smtp.gmail.com",
        "smtp_port": 587,
        "smtp_username": "",
        "smtp_password": "",
        "from_email": "noreply@gift-advisor.com",
        "admin_email": "admin@gift-advisor.com"
    }
    
    @validator("DATABASE_URL")
    def validate_database_url(cls, v):
        """验证数据库URL"""
        if not v:
            raise ValueError("DATABASE_URL不能为空")
        return v
    
    @validator("JWT_SECRET_KEY")
    def validate_jwt_secret_key(cls, v):
        """验证JWT密钥"""
        if v == "your-jwt-secret-key-change-in-production":
            raise ValueError("请修改JWT_SECRET_KEY为安全的随机字符串")
        return v
    
    class Config:
        env_file = ".env"
        case_sensitive = True

# 创建全局配置实例
settings = Settings()