from os import environ
from os.path import exists

from pydantic import Field, model_validator
from pydantic_extra_types.semantic_version import SemanticVersion
from pydantic_settings import BaseSettings, SettingsConfigDict


def get_version():
    if exists('.version'):
        with open('.version', encoding='utf-8') as f:
            return SemanticVersion.parse(f.read().strip())

    return SemanticVersion.parse('0.0.0')


class Settings(BaseSettings):
    model_config = SettingsConfigDict(
        env_file='.env',
        validate_default=False,
        extra='ignore',
    )

    # App info
    APP_NAME: str = 'Hospital Assistant API'
    APP_DESCRIPTION: str = 'API for the Hospital Assistant'
    APP_PORT: int = Field(default=6767)
    VERSION: SemanticVersion = Field(default_factory=get_version)
    DEBUG: bool = Field(default=False)

    # Security
    SECRET_KEY: str = Field(default='secret')
    ALGORITHM: str = 'HS256'

    # Database
    DATABASE_URL: str = Field(default='sqlite:///sql.db')

    # Redis
    REDIS_URL: str = Field(default='redis://localhost:6379/0')

    # Loki Logging
    LOKI_URL: str | None = Field(default=None)

    # ESIA
    ESIA_BASE_URL: str = Field(default='https://esia.gosuslugi.ru')
    ESIA_CLIENT_ID: str = Field(default='')
    ESIA_REDIRECT_URI: str = Field(default='')
    ESIA_CONTAINER_PASSWORD: str = Field(default='')
    ESIA_CONTAINER_THUMBPRINT: str = Field(default='')
    ESIA_PROXY: str | None = Field(default=None)

    ESIA_MAX_REDIRECT_URI: str = Field(default='')

    # Vitacore
    VITACORE_BASE_URL: str = Field(
        default='https://gist-cws.ezdrav.ru:8899/MP_API'
    )
    VITACORE_USERNAME: str = Field(default='')
    VITACORE_PASSWORD: str = Field(default='')

    # AEMD
    AEMD_BASE_URL: str = Field(
        default='http://gist-sdw.ezdrav.ru:8708/EMDAService'
    )
    AEMD_TOKEN: str = Field(default='')

    # TDN
    TDN_BASE_URL: str = Field(default='https://tdn.tatar.ru/api')
    TDN_LOGIN: str = Field(default='')
    TDN_PASSWORD: str = Field(default='')

    # TMK
    TMK_BASE_URL: str = Field(default='https://tmk-api.tatar.ru/api')
    TMK_LOGIN: str = Field(default='admin')
    TMK_PASSWORD: str = Field(default='12345')

    @model_validator(mode='after')
    def celery_env(self):
        environ['CELERY_BROKER_URL'] = self.REDIS_URL
        environ['CELERY_RESULT_BACKEND'] = self.REDIS_URL

        return self


settings = Settings()
