"""Install secrets must never be poisoned by sqlite test DATABASE_URL."""

from __future__ import annotations

import os
from pathlib import Path

import pytest

from app.core import install_secrets as mod


def test_adopt_from_environment_ignores_sqlite(monkeypatch):
    monkeypatch.setenv("DATABASE_URL", "sqlite+pysqlite:///:memory:")
    adopted = mod._adopt_from_environment()
    assert "DATABASE_URL" not in adopted


def test_ensure_install_secrets_rejects_sqlite_install_env(tmp_path, monkeypatch):
    secrets_dir = tmp_path / "secrets"
    secrets_dir.mkdir()
    install_file = secrets_dir / "install.env"
    install_file.write_text(
        "DATABASE_URL=sqlite+pysqlite:////tmp/bad.db\n"
        "JWT_ACCESS_SECRET=x\n"
        "JWT_REFRESH_PEPPER=y\n"
        "POSTGRES_PASSWORD=z\n"
        "SECRETS_LOCKED=true\n",
        encoding="utf-8",
    )
    monkeypatch.setenv("COMPTON_INSTALL_SECRETS_DIR", str(secrets_dir))
    monkeypatch.setattr(mod, "INSTALL_SECRETS_DIR", secrets_dir)
    monkeypatch.setattr(mod, "INSTALL_SECRETS_FILE", install_file)
    with pytest.raises(RuntimeError, match="PostgreSQL"):
        mod.ensure_install_secrets()


def test_docker_entrypoint_rejects_sqlite(monkeypatch):
    from scripts import docker_entrypoint

    monkeypatch.setattr(
        docker_entrypoint.settings,
        "database_url",
        "sqlite+pysqlite:////tmp/bad.db",
    )
    with pytest.raises(RuntimeError, match="SQLite"):
        docker_entrypoint.wait_for_database(max_attempts=1, delay_seconds=0)
