"""Preflight must catch the credential `--bare` will not read.

Discovered by running the CLI against a non-Python repo with a normal
subscription login and no API key: `claude --version` succeeded, preflight
passed, all 18 trials failed "Not logged in", and the run still rendered a
report — with a PR comment reading "no regression detected" over zero
measurements. A 100% failure rate that looks like data is the exact failure
mode this project exists to avoid, so the check is here rather than in the
report.
"""

from __future__ import annotations

from ablate.agents.claude_code import (
    BARE_AUTH_ENV,
    INJECTION_NATIVE,
    NO_BARE_AUTH,
    ClaudeCodeAdapter,
    bare_auth_available,
)


def test_no_credentials_means_bare_cannot_authenticate():
    assert bare_auth_available({}) is False


def test_oauth_login_does_not_satisfy_bare():
    """The trap: the user is logged in, and --bare still cannot use it.

    `--bare` documents that OAuth and the keychain are never read. A login that
    makes interactive `claude` work therefore says nothing about whether a
    trial can run, which is why this is checked by variable rather than by
    asking whether the user "is logged in".
    """
    assert bare_auth_available({"CLAUDE_CODE_OAUTH_TOKEN": "present"}) is False


def test_each_documented_variable_satisfies_bare():
    for name in BARE_AUTH_ENV:
        assert bare_auth_available({name: "set"}) is True, name


def test_empty_string_is_not_a_credential():
    """An exported-but-empty variable is the shape a broken CI secret takes."""
    assert bare_auth_available({"ANTHROPIC_API_KEY": ""}) is False


def test_preflight_reports_the_auth_sentinel(monkeypatch):
    for name in BARE_AUTH_ENV:
        monkeypatch.delenv(name, raising=False)

    result = ClaudeCodeAdapter().preflight()

    assert result.ok is False
    # A sentinel, not prose: the CLI branches on it to offer the choice between
    # setting a key and dropping --bare.
    assert result.detail == NO_BARE_AUTH


def test_native_injection_does_not_require_an_api_key(monkeypatch):
    """Route 2 out of the auth prompt has to actually work.

    Without --bare the CLI reads the ordinary login, so demanding a key here
    would refuse a run that would have succeeded.
    """
    for name in BARE_AUTH_ENV:
        monkeypatch.delenv(name, raising=False)

    result = ClaudeCodeAdapter(injection=INJECTION_NATIVE).preflight()

    assert result.detail != NO_BARE_AUTH


def test_api_key_passes_preflight(monkeypatch):
    monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-ant-test")

    assert ClaudeCodeAdapter().preflight().ok is True
