"""Tests for autodebug/oauth.py — PKCE and device auth flows."""

from __future__ import annotations

from unittest.mock import MagicMock, patch

import pytest

from autodebug.oauth import (
    DEVICE_CODE_TIMEOUT,
    DEVICE_POLL_INTERVAL,
    PKCE_CHALLENGE_METHOD,
    PKCE_VERIFIER_LENGTH,
)


def test_pkce_constants():
    """PKCE constants are reasonable."""
    assert PKCE_VERIFIER_LENGTH >= 32
    assert PKCE_CHALLENGE_METHOD == "S256"


def test_device_flow_constants():
    """Device flow constants are reasonable."""
    assert DEVICE_POLL_INTERVAL >= 1
    assert DEVICE_CODE_TIMEOUT >= 60


def test_generate_pkce_pair():
    """PKCE pair has expected verifier length and distinct challenge."""
    from autodebug.oauth import generate_pkce_pair

    pair = generate_pkce_pair()
    assert len(pair.verifier) >= 43  # Base64url of 32+ bytes
    assert all(c.isalnum() or c in "-_" for c in pair.verifier)
    assert len(pair.challenge) > 0
    assert pair.challenge != pair.verifier


def test_pkce_challenge_deterministic():
    """Same verifier always produces the same challenge."""
    from autodebug.oauth import generate_pkce_pair
    import hashlib
    import base64

    pair = generate_pkce_pair()
    # Manually compute expected challenge
    expected_hash = hashlib.sha256(pair.verifier.encode("ascii")).digest()
    expected_challenge = base64.urlsafe_b64encode(expected_hash).rstrip(b"=").decode("ascii")
    assert pair.challenge == expected_challenge
