from pathlib import Path

from hockey_data.config import HockeySettingsStore

ROOT = Path(__file__).resolve().parents[1]


def test_git_tracks_ui_settings_but_keeps_credentials_local():
    text = (ROOT / ".gitignore").read_text(encoding="utf-8")
    assert "settings/*" in text
    assert "!settings/ui_builder_draft.json" in text
    assert "!settings/ui_builder_published.json" in text
    assert "!settings/hockey_api.json" in text
    assert "settings/stat2tv_credentials.local.json" in text
    assert "settings/editor_security.json" in text


def test_stat2tv_env_credentials_override_local_file(tmp_path, monkeypatch):
    store = HockeySettingsStore(tmp_path / "settings")
    store.secret_file.write_text(
        '{"username":"file-user","password":"file-pass"}',
        encoding="utf-8",
    )
    monkeypatch.setenv("STAT2TV_LOGIN", "env-user")
    monkeypatch.setenv("STAT2TV_PASSWORD", "env-pass")

    assert store.credentials() == ("env-user", "env-pass")
    status = store.status()
    assert status["credentials_configured"] is True
    assert status["credentials_source"] == "env"
    assert "env-pass" not in str(status)


def test_local_credentials_remain_fallback_without_env(tmp_path, monkeypatch):
    monkeypatch.delenv("STAT2TV_LOGIN", raising=False)
    monkeypatch.delenv("STAT2TV_PASSWORD", raising=False)
    store = HockeySettingsStore(tmp_path / "settings")
    store.secret_file.write_text(
        '{"username":"file-user","password":"file-pass"}',
        encoding="utf-8",
    )

    assert store.credentials() == ("file-user", "file-pass")
    assert store.status()["credentials_source"] == "local_file"


def test_production_env_file_fallback_is_present():
    app = (ROOT / "app.py").read_text(encoding="utf-8")
    assert 'HOCKEY_ENV_FILE' in app
    assert '"/mnt/khl/.env"' in app
    assert 'load_dotenv(_external_env, override=False)' in app


def test_admin_diagnostics_reports_credential_source_without_secret():
    router = (ROOT / "hockey_data" / "router.py").read_text(encoding="utf-8")
    js = (ROOT / "hockey_data" / "static" / "tournament-menu.js").read_text(encoding="utf-8")
    assert '"credentials_source": settings_status.get("credentials_source", "missing")' in router
    assert "Credentials source" in js
