import dotenv, os, sys
from pathlib import Path
from loguru import logger


def load_env():
    # 显式指定UTF-8编码加载.env文件
    dotenv.load_dotenv(encoding="utf-8")

    # 从环境变量中获取OpenAI API密钥和基础URL
    os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY")
    os.environ["OPENAI_BASE_URL"] = os.getenv("OPENAI_BASE_URL")

    # 从环境变量中获取Deepseek API密钥和基础URL
    os.environ["DEEPSEEK_API_KEY"] = os.getenv("DEEPSEEK_API_KEY")
    os.environ["DEEPSEEK_BASE_URL"] = os.getenv("DEEPSEEK_BASE_URL")

    # 从环境变量中获取Langsmith API密钥和项目
    os.environ["LANGSMITH_API_KEY"] = os.getenv("LANGSMITH_API_KEY")
    os.environ["LANGSMITH_PROJECT"] = os.getenv("LANGSMITH_PROJECT")

    # 从环境变量中获取Tavily API密钥
    os.environ["TRAILY_API_KEY"] = os.getenv("TRAILY_API_KEY")

    # 服务器配置
    os.environ["HOST"] = os.getenv("HOST", "localhost")
    os.environ["PORT"] = os.getenv("PORT", "8000")
    os.environ["DEBUG"] = os.getenv("DEBUG", "True")

    # 日志配置
    os.environ["LOG_LEVEL"] = os.getenv("LOG_LEVEL", "INFO")

    # 模型配置
    os.environ["DEFAULT_MODEL"] = os.getenv("DEFAULT_MODEL", "gpt-4o-mini")
    os.environ["MAX_TOKENS"] = os.getenv("MAX_TOKENS", "2048")
    os.environ["TEMPERATURE"] = os.getenv("TEMPERATURE", "0.7")

    os.environ["TESSDATA_PREFIX"] = os.getenv(
        "TESSDATA_PREFIX", r"C:\ProgramData\anaconda3\envs\rag\share\tessdata"
    )
    logger.info("环境变量加载成功")

def print_env():
    """打印当前环境变量"""
    logger.info("当前环境变量:")
    for key, value in os.environ.items():
        logger.info(f"{key}: {value}")

def check_environment():
    # 添加当前目录到 Python 路径
    current_dir = Path(__file__).parent
    sys.path.insert(0, str(current_dir))
    try:
        import imageio_ffmpeg
    except ImportError as e:
        logger.error(f"⚠️  imageio_ffmpeg 模块未安装，跳过 FFmpeg 检查: {e}")
    """检查环境配置"""
    logger.info("🔍 检查环境配置...")

    # 尝试导入 imageio_ffmpeg 并获取 FFmpeg 路径
    try:
        ffmpeg_path = imageio_ffmpeg.get_ffmpeg_exe()
        logger.info(f"✅ 已找到 FFmpeg 路径: {ffmpeg_path}")
        os.environ["IMAGEIO_FFMPEG_EXE"] = ffmpeg_path
    except ImportError:
        logger.warning("⚠️  imageio_ffmpeg 模块未安装，跳过 FFmpeg 检查")
    except Exception as e:
        logger.warning(f"⚠️  获取 FFmpeg 路径失败: {e}")

    # 检查 .env 文件
    env_file = current_dir.parent / ".env"
    if not env_file.exists():
        logger.warning(f"⚠️  未找到 .env 文件{env_file}，使用默认配置")
        logger.warning(f"💡 建议创建 .env 文件{env_file}并配置 OPENAI_API_KEY")

    # 检查 OpenAI API Key
    api_key = os.getenv("OPENAI_API_KEY")
    if not api_key:
        logger.warning("⚠️  未配置 OPENAI_API_KEY")
        logger.warning("💡 请在 .env 文件中设置: OPENAI_API_KEY=your_api_key")
    else:
        logger.info(f"✅ OpenAI API Key 已配置 (前6位: {api_key[:6]}...)")

    # 检查日志目录
    logs_dir = current_dir / "logs"
    if not logs_dir.exists():
        logs_dir.mkdir(exist_ok=True)
        logger.warning(f"📁 创建日志目录: {logs_dir}")

    logger.info("✅ 环境检查完成\n")


def install_dependencies():
    """检查并安装依赖"""
    logger.info("📦 检查依赖包...")

    try:
        import fastapi
        import uvicorn
        import langchain

        logger.info("✅ 主要依赖包已安装")
    except ImportError as e:
        logger.error(f"❌ 缺少依赖包: {e}")
        logger.error("💡 请运行: pip install -r requirements.txt")
        return False

    return True


from typing import List
from pydantic_settings import BaseSettings


class Settings(BaseSettings):
    """应用配置"""

    # OpenAI 配置
    openai_api_key: str = ""
    openai_base_url: str = "https://api.openai.com/v1"

    # OpenXLab 配置
    open_x_lab_ak: str = ""
    open_x_lab_sk: str = ""

    # DashScope 配置
    dashscope_api_key: str = ""
    dashscope_base_url: str = ""

    # Firecrawl 配置
    firecrawl_api_key: str = ""

    # DeepSeek 配置
    deepseek_api_key: str = ""
    deepseek_base_url: str = ""

    # LangSmith 配置
    langsmith_project: str = ""
    langsmith_api_key: str = ""

    # Traily 配置
    traily_api_key: str = ""

    # 服务器配置
    host: str = "localhost"
    port: int = 8000
    debug: bool = True

    # CORS 配置
    allowed_origins: List[str] = ["*"]

    # 日志配置
    log_level: str = "INFO"
    log_file: str = "logs/app.log"

    # 模型配置
    default_model: str = "gpt-4o"
    max_tokens: int = 2048
    temperature: float = 0.7

    class Config:
        env_file = ".env"
        env_file_encoding = "utf-8"


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