from __future__ import annotations

from pathlib import Path

import pytest

from jarvis_finance.config.settings import load_settings


def test_runtime_default_outside_repo(tmp_path: Path) -> None:
    repo = tmp_path / "repo"
    repo.mkdir()
    (repo / "pyproject.toml").write_text("[project]\nname='demo'\n")
    settings = load_settings(repo_root=repo, environ={})
    assert "jarvis_runtime/finance-system" in settings.runtime_paths.base_dir.as_posix()
    assert not settings.runtime_paths.base_dir.as_posix().startswith(repo.as_posix())


def test_runtime_inside_repo_is_blocked(tmp_path: Path) -> None:
    repo = tmp_path / "repo"
    repo.mkdir()
    (repo / "pyproject.toml").write_text("[project]\nname='demo'\n")
    with pytest.raises(ValueError, match="outside the Git repository"):
        load_settings(repo_root=repo, environ={"JARVIS_FINANCE_RUNTIME_DIR": str(repo / "runtime")})


def test_test_and_uat_runtime_must_be_explicitly_isolated_below_tmp(tmp_path: Path) -> None:
    repo = tmp_path / "repo"
    repo.mkdir()
    (repo / "pyproject.toml").write_text("[project]\nname='demo'\n")
    productive = Path("~/jarvis_runtime/finance-system").expanduser()
    with pytest.raises(ValueError, match="below /tmp"):
        load_settings(repo_root=repo, environ={"JARVIS_FINANCE_ENV": "test", "JARVIS_FINANCE_RUNTIME_DIR": str(productive)})
    with pytest.raises(ValueError, match="below /tmp"):
        load_settings(repo_root=repo, environ={"JARVIS_FINANCE_ENV": "uat", "JARVIS_FINANCE_DB_PATH": str(productive / "data/finance.sqlite3")})
    isolated = load_settings(
        repo_root=repo,
        environ={
            "JARVIS_FINANCE_ENV": "uat",
            "JARVIS_FINANCE_RUNTIME_DIR": str(tmp_path / "uat-runtime"),
            "JARVIS_FINANCE_DB_PATH": str(tmp_path / "uat.sqlite3"),
        },
    )
    assert isolated.db_path == tmp_path / "uat.sqlite3"
