"""Test OAuth CLI commands."""
import pytest
import tempfile
from pathlib import Path
from typer.testing import CliRunner
from nanobot.cli.oauth import oauth_app


@pytest.fixture
def runner():
    return CliRunner()


def test_oauth_login_help(runner):
    """Login command should have help text."""
    result = runner.invoke(oauth_app, ["login", "--help"])
    assert result.exit_code == 0
    assert "token" in result.output.lower()


def test_oauth_status_no_credentials(runner, tmp_path, monkeypatch):
    """Status should show no credentials when none exist."""
    monkeypatch.setenv("HOME", str(tmp_path))
    result = runner.invoke(oauth_app, ["status"])
    assert result.exit_code == 0
    assert "No OAuth credentials" in result.output


def test_oauth_login_and_status(runner, tmp_path, monkeypatch):
    """Login should save credentials, status should show them."""
    monkeypatch.setenv("HOME", str(tmp_path))
    result = runner.invoke(oauth_app, ["login", "--token", "sk-ant-oat01-test-xxx"])
    assert result.exit_code == 0
    assert "Successfully saved" in result.output

    result = runner.invoke(oauth_app, ["status"])
    assert result.exit_code == 0
    assert "sk-ant-oat01-test-x" in result.output


def test_oauth_logout(runner, tmp_path, monkeypatch):
    """Logout should remove credentials."""
    monkeypatch.setenv("HOME", str(tmp_path))
    runner.invoke(oauth_app, ["login", "--token", "sk-ant-oat01-test-xxx"])
    result = runner.invoke(oauth_app, ["logout"])
    assert result.exit_code == 0
    assert "Removed" in result.output


def test_oauth_login_invalid_token(runner, tmp_path, monkeypatch):
    """Login should reject non-OAuth tokens."""
    monkeypatch.setenv("HOME", str(tmp_path))
    result = runner.invoke(oauth_app, ["login", "--token", "sk-ant-api03-regular"])
    assert result.exit_code == 0
    assert "Invalid token" in result.output
