import os
import platform


def get_environment():
    """
    获取当前运行环境
    优先级：
    1. 环境变量 FLASK_ENV
    2. 根据操作系统自动判断（Windows -> development, Linux -> production）
    """
    # 首先检查环境变量
    env = os.environ.get("FLASK_ENV")
    if env:
        return env.lower()

    # 根据操作系统判断
    system = platform.system().lower()
    if system == "windows":
        return "development"
    elif system == "linux":
        return "production"
    else:
        return "development"  # 其他系统默认使用开发环境


class BaseConfig:
    """基础配置类，包含所有环境共享的配置"""

    SECRET_KEY = os.environ.get("SECRET_KEY") or "you-will-never-guess"
    JSON_AS_ASCII = False
    JSONIFY_PRETTYPRINT_REGULAR = True
    JSON_SORT_KEYS = False

    # 平台特定配置
    PLATFORM = platform.system().lower()

    # 文件上传配置
    ALLOWED_EXTENSIONS = {
        "txt",
        "pdf",
        "png",
        "jpg",
        "jpeg",
        "gif",
        "xlsx",
        "xls",
        "csv",
        "sql",
        "dll",
        "docx",
        "doc",
    }

    # 数据抽取配置
    DATA_EXTRACT_BATCH_SIZE = 1000  # 每批处理的记录数

    # PostgreSQL 基础配置
    SQLALCHEMY_ENGINE_OPTIONS = {
        "pool_pre_ping": True,
        "pool_recycle": 300,
        "pool_size": 10,
        "max_overflow": 20,
    }

    # LLM基础配置
    LLM_BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"
    LLM_MODEL_NAME = "qwen-turbo"
    # LLM_API_KEY = os.environ.get('LLM_API_KEY', "sk-86d4622141d74e9a8d7c38ee873c4d91")
    LLM_API_KEY = os.environ.get("LLM_API_KEY", "sk-db68e37f00974031935395315bfe07f0")

    # Qwen VL模型配置 - 用于图片解析
    QWEN_API_KEY = os.environ.get("QWEN_API_KEY", "sk-db68e37f00974031935395315bfe07f0")
    QWEN_API_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation"

    # Qwen API配置 - 用于文本生成（替代Deepseek）
    QWEN_TEXT_API_KEY = os.environ.get(
        "QWEN_TEXT_API_KEY", "sk-db68e37f00974031935395315bfe07f0"
    )
    QWEN_TEXT_BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"
    QWEN_TEXT_MODEL = "qwen-turbo"

    # 日志基础配置
    LOG_FORMAT = "%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s"
    LOG_ENCODING = "UTF-8"
    LOG_ENABLED = True

    # n8n 工作流引擎配置
    N8N_API_URL = os.environ.get("N8N_API_URL", "https://n8n.citupro.com")
    N8N_API_KEY = os.environ.get(
        "N8N_API_KEY",
        "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI4MTcyNzlmMC1jNTQwLTQyMTEtYjczYy1mNjU4OTI5NTZhMmUiLCJpc3MiOiJuOG4iLCJhdWQiOiJwdWJsaWMtYXBpIiwiaWF0IjoxNzY2NTcyMDg0fQ.QgiUa5tEM1IGZSxhqFaWtdKvwk1SvoRmqdRovTT254M",
    )
    N8N_API_TIMEOUT = int(os.environ.get("N8N_API_TIMEOUT", "30"))


class DevelopmentConfig(BaseConfig):
    """Windows 开发环境配置"""

    FLASK_ENV = "development"
    DEBUG = True
    PORT = 5500

    # 开发环境 MinIO 配置
    MINIO_HOST = "localhost:9000"
    MINIO_USER = "citu-test"
    MINIO_PASSWORD = "citu-test"
    MINIO_SECURE = False
    MINIO_BUCKET = "dataops-bucket"
    PREFIX = ""

    # 开发环境 PostgreSQL 配置
    SQLALCHEMY_DATABASE_URI = "postgresql://postgres:postgres@localhost:5432/dataops"

    # 开发环境 Neo4j 配置
    NEO4J_URI = "bolt://localhost:7687"
    NEO4J_HTTP_URI = "http://localhost:7474"
    NEO4J_USER = "neo4j"
    NEO4J_PASSWORD = "Passw0rd"
    NEO4J_ENCRYPTED = False

    # 开发环境文件路径配置
    UPLOAD_BASE_PATH = "C:\\tmp\\upload"
    ARCHIVE_BASE_PATH = "C:\\tmp\\archive"

    # 开发环境日志配置
    LOG_LEVEL = "DEBUG"
    LOG_FILE = "flask_development.log"
    LOG_TO_CONSOLE = True

    # 开发环境 Airflow 配置
    AIRFLOW_BASE_URL = "http://localhost:8080"
    AIRFLOW_AUTH_USER = "admin"
    AIRFLOW_AUTH_PASSWORD = "admin"


class ProductionConfig(BaseConfig):
    """Linux 生产环境配置"""

    FLASK_ENV = "production"
    DEBUG = False
    PORT = 80

    # 生产环境 MinIO 配置
    MINIO_HOST = "192.168.3.143:9000"
    MINIO_USER = "citu-dataops-acc-key"
    MINIO_PASSWORD = "citu-dataops-secret-key"
    MINIO_SECURE = False
    MINIO_BUCKET = "dataops-bucket"
    PREFIX = ""

    # 生产环境 PostgreSQL 配置
    SQLALCHEMY_DATABASE_URI = os.environ.get(
        "DATABASE_URL", "postgresql://postgres:dataOps@192.168.3.143:5432/dataops"
    )

    # 生产环境 Neo4j 配置
    NEO4J_URI = os.environ.get("NEO4J_URI", "bolt://192.168.3.143:7687")
    NEO4J_HTTP_URI = os.environ.get("NEO4J_HTTP_URI", "http://192.168.3.143:7474")
    NEO4J_USER = os.environ.get("NEO4J_USER", "neo4j")
    NEO4J_PASSWORD = os.environ.get("NEO4J_PASSWORD", "cituneo4j")
    NEO4J_ENCRYPTED = False

    # 生产环境文件路径配置
    UPLOAD_BASE_PATH = "/data/upload"
    ARCHIVE_BASE_PATH = "/data/archive"

    # 生产环境日志配置
    LOG_LEVEL = "INFO"
    LOG_FILE = "flask_production.log"
    LOG_TO_CONSOLE = False

    # 生产环境 Airflow 配置
    AIRFLOW_BASE_URL = os.environ.get("AIRFLOW_BASE_URL", "http://192.168.3.143:8080")
    AIRFLOW_AUTH_USER = os.environ.get("AIRFLOW_AUTH_USER", "admin")
    AIRFLOW_AUTH_PASSWORD = os.environ.get("AIRFLOW_AUTH_PASSWORD", "admin")


# 配置字典
config = {
    "development": DevelopmentConfig,
    "production": ProductionConfig,
    "default": DevelopmentConfig,
}

# 获取当前环境
current_env = get_environment()
