from pathlib import Path
from pydantic_settings import BaseSettings, SettingsConfigDict

BASE_DIR = Path(__file__).resolve().parents[2]
ENV_FILE = BASE_DIR / ".env"
PLACEHOLDER_SECRET_VALUES = {
    "",
    "your-super-secret-key-change-this",
    "admin-secret-token-change-this",
}


def resolve_database_url(raw_url: str) -> str:
    """Resolve relative SQLite paths against the Server directory."""
    if not raw_url.startswith("sqlite:///"):
        return raw_url

    sqlite_path = raw_url.removeprefix("sqlite:///")
    if not sqlite_path or sqlite_path == ":memory:":
        return raw_url

    path_obj = Path(sqlite_path)
    if path_obj.is_absolute():
        return raw_url

    return f"sqlite:///{(BASE_DIR / path_obj).resolve().as_posix()}"

class Settings(BaseSettings):
    ENV: str = "development"
    PROJECT_NAME: str = "DesignerCEP Backend"
    API_V1_STR: str = "/api/v1"
    DATABASE_URL: str = "sqlite:///./designercep.db"
    SECRET_KEY: str = ""  # 必须从 .env 读取
    ACCESS_TOKEN_EXPIRE_MINUTES: int = 10080
    
    ALLOWED_ORIGINS: str = "*"
    ADMIN_TOKEN: str = ""  # 必须从 .env 读取

    # Email Configuration
    SMTP_HOST: str = "smtp.gmail.com"
    SMTP_PORT: int = 587
    SMTP_USER: str = ""
    SMTP_PASSWORD: str = ""  # 必须从 .env 读取
    EMAILS_FROM_EMAIL: str = ""
    EMAILS_FROM_NAME: str = "Designer"
    
    # 七牛云对象存储
    QINIU_ACCESS_KEY: str = ""
    QINIU_SECRET_KEY: str = ""
    QINIU_BUCKET: str = ""
    QINIU_DOMAIN: str = ""
    
    # AI 配置
    AI_PROVIDER: str = "ark"
    AI_API_KEY: str = ""
    AI_BASE_URL: str = "https://ark.cn-beijing.volces.com/api/v3"
    AI_CHAT_BASE_URL: str = ""
    AI_VISION_BASE_URL: str = ""
    AI_IMAGE_BASE_URL: str = ""
    AI_MODEL: str = "doubao-seed-2-0-mini-260215"
    AI_VISION_MODEL: str = "doubao-seed-2-0-mini-260215"
    AI_IMAGE_EDIT_MODEL: str = "doubao-seedream-5-0-260128"
    AI_CHAT_MODELS: str = ""
    AI_VISION_MODELS: str = ""
    AI_IMAGE_EDIT_MODELS: str = ""

    # 兼容旧字段
    ARK_API_KEY: str = ""
    ARK_BASE_URL: str = "https://ark.cn-beijing.volces.com/api/v3"
    
    model_config = SettingsConfigDict(
        env_file=ENV_FILE,
        env_file_encoding="utf-8",
        extra="ignore"
    )

    def runtime_warnings(self) -> list[str]:
        warnings: list[str] = []
        if not ENV_FILE.exists():
            warnings.append("未找到 Server/.env，当前使用的是代码默认配置。")
        if self.SECRET_KEY in PLACEHOLDER_SECRET_VALUES:
            warnings.append("SECRET_KEY 仍是默认值，请在部署前替换。")
        if self.ADMIN_TOKEN in PLACEHOLDER_SECRET_VALUES:
            warnings.append("ADMIN_TOKEN 仍是默认值，请在部署前替换。")
        if not self.AI_API_KEY and not self.ARK_API_KEY:
            warnings.append("AI_API_KEY / ARK_API_KEY 未配置；如果走用户自带 Key 模式可忽略此项。")
        return warnings

settings = Settings()
settings.DATABASE_URL = resolve_database_url(settings.DATABASE_URL)
