"""Tests for specter_cli.auth — authentication."""

from __future__ import annotations

from pathlib import Path

import pytest

from specter_cli.auth import read_ssh_public_key, require_auth
from specter_cli.config import save_auth


@pytest.fixture(autouse=True)
def _isolated_config(tmp_path, monkeypatch):
    """Redirect config to temp directory via SPECTER_HOME."""
    sd = tmp_path / ".specter"
    sd.mkdir()
    monkeypatch.setenv("SPECTER_HOME", str(sd))
    # Ensure SPECTER_API_KEY is not set by default.
    monkeypatch.delenv("SPECTER_API_KEY", raising=False)


class TestRequireAuth:
    def test_returns_token_when_logged_in(self):
        save_auth("sp_live_test123", method="device_auth")
        assert require_auth() == "sp_live_test123"

    def test_exits_when_not_logged_in(self):
        with pytest.raises(SystemExit) as exc_info:
            require_auth()
        assert exc_info.value.code == 1

    def test_env_var_takes_precedence(self, monkeypatch):
        """SPECTER_API_KEY env var should be returned over stored token."""
        save_auth("sp_live_stored", method="device_auth")
        monkeypatch.setenv("SPECTER_API_KEY", "sp_live_env_key")
        assert require_auth() == "sp_live_env_key"

    def test_empty_env_var_ignored(self, monkeypatch):
        """Empty SPECTER_API_KEY should fall through to auth.json."""
        monkeypatch.setenv("SPECTER_API_KEY", "")
        with pytest.raises(SystemExit):
            require_auth()


class TestReadSshPublicKey:
    def test_reads_ed25519_key(self, tmp_path, monkeypatch):
        ssh_dir = tmp_path / ".ssh"
        ssh_dir.mkdir()
        key_file = ssh_dir / "id_ed25519.pub"
        key_file.write_text("ssh-ed25519 AAAA... test@host\n")

        monkeypatch.setattr(Path, "home", lambda: tmp_path)
        key = read_ssh_public_key()
        assert key == "ssh-ed25519 AAAA... test@host"

    def test_reads_rsa_key(self, tmp_path, monkeypatch):
        ssh_dir = tmp_path / ".ssh"
        ssh_dir.mkdir()
        key_file = ssh_dir / "id_rsa.pub"
        key_file.write_text("ssh-rsa AAAA... test@host\n")

        monkeypatch.setattr(Path, "home", lambda: tmp_path)
        key = read_ssh_public_key()
        assert key == "ssh-rsa AAAA... test@host"

    def test_no_key_raises(self, tmp_path, monkeypatch):
        ssh_dir = tmp_path / ".ssh"
        ssh_dir.mkdir()

        monkeypatch.setattr(Path, "home", lambda: tmp_path)
        with pytest.raises(FileNotFoundError, match="ssh-keygen"):
            read_ssh_public_key()

    def test_prefers_ed25519_over_rsa(self, tmp_path, monkeypatch):
        ssh_dir = tmp_path / ".ssh"
        ssh_dir.mkdir()
        (ssh_dir / "id_ed25519.pub").write_text("ssh-ed25519 PREFERRED")
        (ssh_dir / "id_rsa.pub").write_text("ssh-rsa FALLBACK")

        monkeypatch.setattr(Path, "home", lambda: tmp_path)
        key = read_ssh_public_key()
        assert key == "ssh-ed25519 PREFERRED"
