import os
from pathlib import Path

import yaml
from pydantic import BaseModel

{% if has_fastapi %}

class AppModel(BaseModel):
    host: str
    port: int
    debug: bool = False

{% endif %}
{% if has_redis %}

class RedisModel(BaseModel):
    host: str
    port: int
    db: int

    @property
    def url(self) -> str:
        return f"redis://{self.host}:{self.port}/{self.db}"

{% endif %}

class Settings(BaseModel):
{% if has_fastapi %}
    app: AppModel
{% endif %}
{% if has_sqlalchemy %}
    database_dsn: str
{% endif %}
{% if has_redis %}
    redis: RedisModel
{% endif %}
{% if has_aiogram %}
    token: str
    updates_strategy: str
{% endif %}


class Config:
    c: Settings | None = None

    def __new__(cls, *args, **kwargs):
        raise RuntimeError("Config should not be instantiated")


def init_config(path: Path | None = None) -> None:
    if path is None:
        path = Path(os.environ.get("CONFIG_PATH", "config/local.yaml"))
    with open(path) as f:
        data = yaml.safe_load(f) or {}
    Config.c = Settings(**data)
