from typing import List, Union
from pydantic_settings import BaseSettings
from pydantic import Field, AnyHttpUrl, validator
import os

class Settings(BaseSettings):
    API_V1_STR: str = "/api/v1"
    SECRET_KEY: str = Field(..., env="SECRET_KEY")
    ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 30  # 30 days

    MYSQL_USER: str = Field(..., env="MYSQL_USER")
    MYSQL_PASSWORD: str = Field(..., env="MYSQL_PASSWORD")
    MYSQL_HOST: str = Field(..., env="MYSQL_HOST")
    MYSQL_PORT: str = Field(..., env="MYSQL_PORT")
    MYSQL_DATABASE: str = Field(..., env="MYSQL_DATABASE")
    
    BACKEND_CORS_ORIGINS: List[AnyHttpUrl] = [
        "http://localhost:3000",                    # React default port
        "http://localhost:8000",                    # Backend API
        "http://localhost:9000",                    # Media server
        "https://adimsayar.s3.eu-central-1.amazonaws.com",  # Media server
        "https://panel.adimsayar.easerver.net/admin",                 # Backend API
        "https://adimsayar.easerver.net",                 # Backend API
    ]
    
    # --- Email configuration ---
    MAIL_MAILER: str = Field(..., env="MAIL_MAILER")
    MAIL_HOST: str = Field(..., env="MAIL_HOST")
    MAIL_PORT: int = Field(..., env="MAIL_PORT")
    MAIL_USERNAME: str = Field(..., env="MAIL_USERNAME")
    MAIL_PASSWORD: str = Field(..., env="MAIL_PASSWORD")
    MAIL_ENCRYPTION: str = Field(..., env="MAIL_ENCRYPTION")
    MAIL_FROM_ADDRESS: str = Field(..., env="MAIL_FROM_ADDRESS")
    
    TIMEZONE: str = os.environ.get("TIMEZONE", "Europe/Istanbul")
    
    # 로컬 스토리지 설정
    STORAGE_BASE_PATH: str = Field("/var/www/adimsayar.easerver.net/htdocs/storage", env="STORAGE_BASE_PATH")
    BASE_URL: str = Field("https://adimsayar.easerver.net", env="BASE_URL")
    
    # Firebase 서비스 계정 설정 (V1 API용)
    FIREBASE_PROJECT_ID: str = Field(..., env="FIREBASE_PROJECT_ID")
    FIREBASE_PRIVATE_KEY: str = Field(..., env="FIREBASE_PRIVATE_KEY")
    FIREBASE_CLIENT_EMAIL: str = Field(..., env="FIREBASE_CLIENT_EMAIL")
    
    # Referral reward configuration (Implement changes via admin panel or inject from DB/environment variables)
    REFERRAL_DIRECT_BONUS_PERCENTAGE: float = 0.5       # 직접 추천 시, 0.5% bonus
    REFERRAL_CHAIN_DECAY: float = 0.5
    REFERRAL_MAX_LEVEL: int = 2
    REFERRAL_SIGNUP_BONUS: int = 100

    # 추가: 달성 목표에 따른 보너스 설정
    ACHIEVEMENT_STEP_GOAL: int = 10000  # 목표 걸음 수
    ACHIEVEMENT_BONUS: int = 100        # 목표 달성 시 지급 보너스 포인트

    @validator("BACKEND_CORS_ORIGINS", pre=True)
    def assemble_cors_origins(cls, v: Union[str, List[str]]) -> Union[List[str], str]:
        if isinstance(v, str) and not v.startswith("["):
            return [i.strip() for i in v.split(",")]
        elif isinstance(v, (list, str)):
            return v
        raise ValueError(v)

    @validator("FIREBASE_PRIVATE_KEY")
    def decode_private_key(cls, v: str) -> str:
        """
        환경 변수에서 개행 문자가 제대로 처리되지 않는 경우를 위한 처리
        """
        if v and "\\n" in v:
            return v.replace("\\n", "\n")
        return v

    class Config:
        case_sensitive = True
        env_file = ".env"  # Tells Pydantic to load these settings from .env
        extra = "allow"    # AWS S3 환경변수 등 추가 환경변수 허용
    
    @property
    def SQLALCHEMY_DATABASE_URI(self) -> str:
        return (
            f"mysql+mysqlconnector://{self.MYSQL_USER}:"
            f"{self.MYSQL_PASSWORD}@{self.MYSQL_HOST}:"
            f"{self.MYSQL_PORT}/{self.MYSQL_DATABASE}"
        )

settings = Settings()
