from __future__ import annotations

from pathlib import Path

import pytest

from dms.config import (
    DEFAULT_STORAGE_ROOT,
    DEFAULT_UI_DICTIONARY_CONFIG_PATH,
    load_dms_config,
)


def test_default_config_uses_mysql_read_committed(monkeypatch):
    for name in (
        "DMS_DATABASE_URL",
        "DMS_STORAGE_ROOT",
        "DMS_MAX_UPLOAD_SIZE",
        "DMS_BATCH_MAX_FILES",
        "DMS_BUSINESS_TIMEZONE",
        "DMS_JWT_SECRET",
        "DMS_UI_DICTIONARY_CONFIG_PATH",
    ):
        monkeypatch.delenv(name, raising=False)

    config = load_dms_config()

    assert config["SQLALCHEMY_DATABASE_URI"].startswith("mysql+pymysql://")
    assert config["SQLALCHEMY_ENGINE_OPTIONS"]["isolation_level"] == "READ COMMITTED"
    assert config["SQLALCHEMY_ENGINE_OPTIONS"]["connect_args"] == {
        "init_command": "SET time_zone = '+00:00'"
    }
    assert config["DMS_STORAGE_ROOT"] == str(DEFAULT_STORAGE_ROOT.resolve())
    assert config["MAX_CONTENT_LENGTH"] == config["DMS_MAX_UPLOAD_SIZE"]
    assert config["DMS_BATCH_MAX_FILES"] == 50
    assert config["DMS_BUSINESS_TIMEZONE"] == "Asia/Shanghai"
    assert config["DMS_JWT_SECRET"] == ""
    assert config["DMS_UI_DICTIONARY_CONFIG_PATH"] == str(
        DEFAULT_UI_DICTIONARY_CONFIG_PATH.resolve()
    )


def test_environment_overrides_are_loaded(monkeypatch, tmp_path: Path):
    monkeypatch.setenv(
        "DMS_DATABASE_URL",
        "mysql+pymysql://example:example@db.invalid:3306/dms?charset=utf8mb4",
    )
    monkeypatch.setenv("DMS_STORAGE_ROOT", str(tmp_path))
    monkeypatch.setenv("DMS_MAX_UPLOAD_SIZE", "2048")
    monkeypatch.setenv("DMS_BATCH_MAX_FILES", "7")
    monkeypatch.setenv("DMS_BUSINESS_TIMEZONE", "UTC")
    monkeypatch.setenv("DMS_JWT_SECRET", "test-only")
    dictionary_path = tmp_path / "external-ui-dictionaries.json"
    monkeypatch.setenv(
        "DMS_UI_DICTIONARY_CONFIG_PATH", str(dictionary_path)
    )

    config = load_dms_config()

    assert config["DMS_STORAGE_ROOT"] == str(tmp_path.resolve())
    assert config["DMS_MAX_UPLOAD_SIZE"] == 2048
    assert config["DMS_BATCH_MAX_FILES"] == 7
    assert config["DMS_BUSINESS_TIMEZONE"] == "UTC"
    assert config["DMS_JWT_SECRET"] == "test-only"
    assert config["DMS_UI_DICTIONARY_CONFIG_PATH"] == str(
        dictionary_path.resolve()
    )


@pytest.mark.parametrize(
    ("name", "value"),
    [
        ("DMS_MAX_UPLOAD_SIZE", "0"),
        ("DMS_MAX_UPLOAD_SIZE", "not-an-int"),
        ("DMS_BATCH_MAX_FILES", "-1"),
    ],
)
def test_invalid_positive_integer_config_is_rejected(monkeypatch, name, value):
    monkeypatch.setenv(name, value)
    with pytest.raises(ValueError):
        load_dms_config()
