"""
應用配置管理
使用 Pydantic Settings 管理環境變數
"""
from typing import List, Union
from pydantic import field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict


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

    # 基本資訊
    PROJECT_NAME: str = "HR Portal API"
    VERSION: str = "2.0.0"
    ENVIRONMENT: str = "development"  # development, staging, production
    HOST: str = "0.0.0.0"
    PORT: int = 8000

    # 資料庫配置 (使用 psycopg 驅動)
    DATABASE_URL: str = "postgresql+psycopg://hr_admin:hr_dev_password_2026@localhost:5433/hr_portal"
    DATABASE_ECHO: bool = False  # SQL 查詢日誌

    # CORS 配置 (字串格式,逗號分隔)
    ALLOWED_ORIGINS: str = "http://localhost:3000,http://10.1.0.245:3000,https://hr.ease.taipei"

    def get_allowed_origins(self) -> List[str]:
        """取得 CORS 允許的來源清單"""
        return [origin.strip() for origin in self.ALLOWED_ORIGINS.split(",")]

    # Keycloak 配置
    KEYCLOAK_URL: str = "https://auth.ease.taipei"
    KEYCLOAK_REALM: str = "porscheworld"
    KEYCLOAK_CLIENT_ID: str = "hr-backend"
    KEYCLOAK_CLIENT_SECRET: str = ""  # 從環境變數讀取
    KEYCLOAK_ADMIN_USERNAME: str = ""
    KEYCLOAK_ADMIN_PASSWORD: str = ""

    # JWT 配置
    JWT_SECRET_KEY: str = "your-secret-key-change-in-production"
    JWT_ALGORITHM: str = "HS256"
    JWT_ACCESS_TOKEN_EXPIRE_MINUTES: int = 30

    # 郵件配置 (Docker Mailserver)
    MAIL_SERVER: str = "10.1.0.30"
    MAIL_PORT: int = 587
    MAIL_USE_TLS: bool = True
    MAIL_ADMIN_USER: str = "admin@porscheworld.tw"
    MAIL_ADMIN_PASSWORD: str = ""

    # NAS 配置 (Synology)
    NAS_HOST: str = "10.1.0.30"
    NAS_PORT: int = 5000
    NAS_USERNAME: str = ""
    NAS_PASSWORD: str = ""
    NAS_WEBDAV_URL: str = "https://nas.lab.taipei/webdav"
    NAS_SMB_SHARE: str = "Working"

    # 日誌配置
    LOG_LEVEL: str = "INFO"
    LOG_FILE: str = "logs/hr_portal.log"

    # 分頁配置
    DEFAULT_PAGE_SIZE: int = 20
    MAX_PAGE_SIZE: int = 100

    # 配額配置 (MB)
    EMAIL_QUOTA_JUNIOR: int = 1000
    EMAIL_QUOTA_MID: int = 2000
    EMAIL_QUOTA_SENIOR: int = 5000
    EMAIL_QUOTA_MANAGER: int = 10000

    # NAS 配額配置 (GB)
    NAS_QUOTA_JUNIOR: int = 50
    NAS_QUOTA_MID: int = 100
    NAS_QUOTA_SENIOR: int = 200
    NAS_QUOTA_MANAGER: int = 500

    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        case_sensitive=True,
    )


# 全域配置實例
settings = Settings()
