from app.db.base import Base
from app.db.session import SessionLocal, engine
from common_logging import get_logger

logger = get_logger(__name__)

PROVIDER_SEEDS = [
    {
        "name": "OpenAI",
        "icon": "openai",
        "color": "#10a37f",
        "default_base_url": "https://api.openai.com/v1",
        "priority": 100,
        "provider_kind": "public_api",
        "protocol": "openai_compatible",
        "auth_type": "bearer",
        "capabilities": ["chat", "embedding"],
        "is_local": False,
    },
    {
        "name": "Anthropic",
        "icon": "anthropic",
        "color": "#d4a574",
        "default_base_url": "https://api.anthropic.com",
        "priority": 90,
        "provider_kind": "public_api",
        "protocol": "anthropic",
        "auth_type": "api_key",
        "capabilities": ["chat"],
        "is_local": False,
    },
    {
        "name": "Google",
        "icon": "google",
        "color": "#4285f4",
        "default_base_url": "https://generativelanguage.googleapis.com/v1beta",
        "priority": 80,
        "provider_kind": "public_api",
        "protocol": "gemini",
        "auth_type": "api_key",
        "capabilities": ["chat", "embedding"],
        "is_local": False,
    },
    {
        "name": "DeepSeek",
        "icon": "deepseek",
        "color": "#1e40af",
        "default_base_url": "https://api.deepseek.com",
        "priority": 70,
        "provider_kind": "public_api",
        "protocol": "openai_compatible",
        "auth_type": "bearer",
        "capabilities": ["chat", "embedding"],
        "is_local": False,
    },
    {
        "name": "阿里云百炼",
        "icon": "alibaba",
        "color": "#ff6a00",
        "default_base_url": "https://dashscope.aliyuncs.com/compatible-mode/v1",
        "priority": 60,
        "provider_kind": "public_api",
        "protocol": "openai_compatible",
        "auth_type": "bearer",
        "capabilities": ["chat", "embedding"],
        "is_local": False,
    },
    {
        "name": "智谱AI",
        "icon": "zhipu",
        "color": "#4169e1",
        "default_base_url": "https://open.bigmodel.cn/api/paas/v4",
        "priority": 50,
        "provider_kind": "public_api",
        "protocol": "openai_compatible",
        "auth_type": "bearer",
        "capabilities": ["chat", "embedding"],
        "is_local": False,
    },
    {
        "name": "Moonshot",
        "icon": "moonshot",
        "color": "#7c3aed",
        "default_base_url": "https://api.moonshot.cn/v1",
        "priority": 40,
        "provider_kind": "public_api",
        "protocol": "openai_compatible",
        "auth_type": "bearer",
        "capabilities": ["chat", "embedding"],
        "is_local": False,
    },
    {
        "name": "百度千帆",
        "icon": "baidu",
        "color": "#2932e1",
        "default_base_url": "https://qianfan.baidubce.com/v2",
        "priority": 30,
        "provider_kind": "public_api",
        "protocol": "openai_compatible",
        "auth_type": "bearer",
        "capabilities": ["chat", "embedding"],
        "is_local": False,
    },
    {
        "name": "Mistral",
        "icon": "mistral",
        "color": "#f2a73b",
        "default_base_url": "https://api.mistral.ai/v1",
        "priority": 20,
        "provider_kind": "public_api",
        "protocol": "openai_compatible",
        "auth_type": "bearer",
        "capabilities": ["chat", "embedding"],
        "is_local": False,
    },
    {
        "name": "火山引擎",
        "icon": "volcengine",
        "color": "#f97316",
        "default_base_url": "https://ark.cn-beijing.volces.com/api/v3",
        "priority": 55,
        "provider_kind": "public_api",
        "protocol": "openai_compatible",
        "auth_type": "bearer",
        "capabilities": ["chat"],
        "is_local": False,
    },
    {
        "name": "Cohere",
        "icon": "cohere",
        "color": "#d946ef",
        "default_base_url": "https://api.cohere.com/v1",
        "priority": 25,
        "provider_kind": "public_api",
        "protocol": "openai_compatible",
        "auth_type": "bearer",
        "capabilities": ["rerank"],
        "is_local": False,
    },
    {
        "name": "本地 vLLM",
        "icon": "server",
        "color": "#6366f1",
        "default_base_url": "http://localhost:8100/v1",
        "base_url": "http://localhost:8100/v1",
        "priority": 10,
        "provider_kind": "self_deployed",
        "protocol": "openai_compatible",
        "auth_type": "bearer",
        "capabilities": ["chat"],
        "is_local": True,
        "configured": True,
        "healthcheck_path": "/health",
        "enabled": True,
    },
    {
        "name": "本地 infinity 向量",
        "icon": "server",
        "color": "#8b5cf6",
        "default_base_url": "http://localhost:8200/v1",
        "base_url": "http://localhost:8200/v1",
        "priority": 10,
        "provider_kind": "self_deployed",
        "protocol": "openai_compatible",
        "auth_type": "bearer",
        "capabilities": ["embedding"],
        "is_local": True,
        "configured": True,
        "healthcheck_path": "/health",
        "enabled": True,
    },
    {
        "name": "本地 infinity 重排",
        "icon": "server",
        "color": "#a78bfa",
        "default_base_url": "http://localhost:8300/v1",
        "base_url": "http://localhost:8300/v1",
        "priority": 10,
        "provider_kind": "self_deployed",
        "protocol": "openai_compatible",
        "auth_type": "bearer",
        "capabilities": ["rerank"],
        "is_local": True,
        "configured": True,
        "healthcheck_path": "/health",
        "enabled": True,
    },
    {
        "name": "本地 MLX",
        "icon": "apple",
        "color": "#374151",
        "default_base_url": "http://localhost:8400/v1",
        "base_url": "http://localhost:8400/v1",
        "priority": 5,
        "provider_kind": "self_deployed",
        "protocol": "openai_compatible",
        "auth_type": "bearer",
        "capabilities": ["chat"],
        "is_local": True,
        "configured": True,
        "healthcheck_path": "/health",
        "enabled": False,
    },
    {
        "name": "自定义",
        "icon": "custom",
        "color": "#6b7280",
        "default_base_url": "",
        "priority": 0,
        "provider_kind": "self_hosted",
        "protocol": "custom_http",
        "auth_type": "none",
        "capabilities": [],
        "is_local": False,
    },
]
MODEL_SEEDS = {
    "本地 vLLM": {
        "code": "local-qwen-chat",
        "name": "Qwen3.5-27B-AWQ (本地)",
        "type": "chat",
        "remote_model_id": "Qwen3.5-27B-AWQ",
        "enabled": True,
        "is_active": True,
    },
    "本地 infinity 向量": {
        "code": "local-bge-m3",
        "name": "bge-m3 (本地)",
        "type": "embedding",
        "dimension": 1024,
        "remote_model_id": "bge-m3",
        "enabled": True,
        "is_active": True,
    },
    "本地 infinity 重排": {
        "code": "local-bge-reranker",
        "name": "bge-reranker-v2-m3 (本地)",
        "type": "rerank",
        "remote_model_id": "bge-reranker-v2-m3",
        "enabled": True,
        "is_active": True,
    },
    "本地 MLX": {
        "code": "local-mlx-chat",
        "name": "Qwen3.5-27B MLX (本地)",
        "type": "chat",
        "remote_model_id": "Qwen3.5-27B",
        "enabled": True,
        "is_active": True,
    },
}


def init_db():
    from app.db.tenant_schema import TenantSchemaManager

    tables_to_create = [
        table
        for table in Base.metadata.tables.values()
        if table.name in TenantSchemaManager.PUBLIC_TABLES
    ]
    Base.metadata.create_all(bind=engine, tables=tables_to_create)
    logger.info("Database tables created")
    _seed_providers()
    logger.info("Database initialization completed")


def _seed_providers():
    from app.models.provider import Model, ModelProvider

    db = SessionLocal()
    try:
        all_providers = db.query(ModelProvider).order_by(ModelProvider.id).all()
        by_name = {}
        duplicates_to_remove = []
        for p in all_providers:
            if p.name not in by_name:
                by_name[p.name] = p
            else:
                model_count = db.query(Model).filter(Model.provider_id == p.id).count()
                if model_count == 0:
                    duplicates_to_remove.append(p)
        for dup in duplicates_to_remove:
            db.delete(dup)
        existing = {p.name: p for p in db.query(ModelProvider).all()}
        for data in PROVIDER_SEEDS:
            provider = existing.get(data["name"])
            if provider:
                for key, value in data.items():
                    setattr(provider, key, value)
            else:
                db.add(ModelProvider(**data))
        db.commit()
        existing_providers = {p.name: p for p in db.query(ModelProvider).all()}
        existing_models = {m.code: m for m in db.query(Model).all()}
        for provider_name, model_data in MODEL_SEEDS.items():
            provider = existing_providers.get(provider_name)
            if not provider:
                continue
            model = existing_models.get(model_data["code"])
            if model:
                model.provider_id = provider.id
                if model.type != model_data.get("type"):
                    model.type = model_data["type"]
                if "enabled" in model_data:
                    model.enabled = model_data["enabled"]
                if "is_active" in model_data:
                    model.is_active = model_data["is_active"]
            else:
                db.add(Model(provider_id=provider.id, **model_data))
        db.commit()
    except Exception as e:
        db.rollback()
        logger.warning(f"Provider seeding failed: {e}")
    finally:
        db.close()
