from __future__ import annotations

import json
import os
from pathlib import Path
import sys
from tempfile import TemporaryDirectory
from unittest.mock import patch

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from financial_system.core.settings import get_settings


def test_database_url_environment_variable_overrides_config_file() -> None:
    with TemporaryDirectory() as temp_dir:
        config_path = Path(temp_dir) / "app_settings.json"
        config_path.write_text(
            json.dumps(
                {
                    "database": {
                        "url": "mysql+pymysql://json-user:json-pass@json-host:3306/financial_system?charset=utf8mb4"
                    }
                }
            ),
            encoding="utf-8",
        )
        docker_database_url = (
            "mysql+pymysql://docker-user:docker-pass@mysql.example.com:3306/"
            "financial_system?charset=utf8mb4"
        )

        with patch.dict(
            os.environ,
            {
                "APP_CONFIG_FILE": str(config_path),
                "DATABASE_URL": docker_database_url,
            },
            clear=False,
        ):
            settings = get_settings()

    assert settings.database_url == docker_database_url


if __name__ == "__main__":
    test_database_url_environment_variable_overrides_config_file()
