# -*- coding: utf-8 -*-
import os
from typing import Optional

# 尝试加载 .env 文件
try:
    from dotenv import load_dotenv
    load_dotenv()
except ImportError:
    pass


class Settings:
    """配置类 - 支持动态设置 API Key"""

    # API 配置 - 从环境变量读取，或通过 set_api_key 动态设置
    _api_key: str = os.getenv("QWEN_API_KEY", "")
    _base_url: str = os.getenv("QWEN_BASE_URL", "https://dashscope.aliyuncs.com/compatible-mode/v1")
    _model: str = os.getenv("QWEN_MODEL", "qwen-plus")

    # 服务配置
    APP_NAME: str = "小红书内容助手"
    VERSION: str = "1.0.0"
    DEBUG: bool = False

    # 数据库配置
    DATABASE_URL: str = "sqlite:///./content_assistant.db"

    # Redis 配置
    REDIS_URL: Optional[str] = None

    @classmethod
    def set_api_key(cls, api_key: str, base_url: str = None, model: str = None):
        """动态设置 API Key"""
        cls._api_key = api_key
        if base_url:
            cls._base_url = base_url
        if model:
            cls._model = model

    @property
    def API_KEY(self) -> str:
        return self._api_key

    @property
    def API_BASE_URL(self) -> str:
        return self._base_url

    @property
    def MODEL(self) -> str:
        return self._model

    def validate(self):
        """验证配置"""
        if not self._api_key:
            raise ValueError(
                "❌ 未配置 API Key！\n"
                "使用方式：\n"
                "1. 命令行传入: python main.py --api-key YOUR_KEY --topic '主题'\n"
                "2. 环境变量: 设置 QWEN_API_KEY 环境变量\n"
                "3. .env 文件: 创建 .env 文件，写入 QWEN_API_KEY=your-key\n"
                "\n获取 API Key: https://dashscope.console.aliyun.com/"
            )
        return True


settings = Settings()
