import tempfile  # for testing purposes
from dataclasses import dataclass, field
from pathlib import Path
from typing import List, Optional

import risc_lasagna
import risc_lasagna.layer as layer


@dataclass
class DatabaseConfig:
    host: str
    port: int
    user: Optional[str] = None
    password: Optional[str] = None


@dataclass
class HealthCheck:
    rate_in_ms: int
    url: str


@dataclass
class ApplicationConfig:
    host: str
    port: int
    elements: List[str]
    health_check: Optional[HealthCheck] = field(default=None)
    protocol: str = field(default="https")
    database_configs: Optional[List[DatabaseConfig]] = field(default=None)


__example_yaml = """
host: remote_host
health_check:
  rate_in_ms: 30
  url: localhost:6543
elements:
  - abc
  - def
  - ghi
database_configs:
  - host: remote_db
    port: 1234
  - host: remote_db
    port: 1234
    user: postgres
    password: super_safe_password
"""


def load_application_config() -> ApplicationConfig:
    # set the environment variable with a prefix
    with tempfile.NamedTemporaryFile() as temp:
        temp.write(bytes(__example_yaml, encoding="utf-8"))
        temp.flush()
        return risc_lasagna.build(
            ApplicationConfig,
            [
                layer.YamlLayer(Path(temp.name)),
                layer.DataClassDefaultLayer(
                    ApplicationConfig(
                        "localhost",
                        12345,
                        ["a", "b", "c"],
                        database_configs=[DatabaseConfig("localhost", 5432)],
                    )
                ),
            ],
        )


if __name__ == "__main__":
    config = load_application_config()
    print(config)
