"""Anthropic SDK client factory — the ONE place auth strategy lives.

JT runs OAuth/Max-subscription only (no ANTHROPIC_API_KEY by design — an API
key would bill API quota instead of the Max plan). The Claude Code OAuth token
(`claude setup-token`, in ~/.zshenv as CLAUDE_CODE_OAUTH_TOKEN, exported as
ANTHROPIC_AUTH_TOKEN) authenticates /v1/messages directly — LIVE-VERIFIED
2026-06-11 (curl + SDK both HTTP 200) — but requires the OAuth beta header
on every request:

    anthropic-beta: oauth-2025-04-20

The SDK does NOT add that header itself, so a bare ``anthropic.Anthropic()``
401s on this setup. Every production SDK call site must construct its client
through :func:`anthropic_client` instead.

Caveats (recoil memory: reference-claude-oauth-token-studio):
- Calls draw on the Max plan's shared rate limits — heavy pipeline use
  competes with interactive Claude Code sessions.
- The token lives ~1 year; rotation reminder is May 2027.
- If BOTH ANTHROPIC_API_KEY and ANTHROPIC_AUTH_TOKEN are set, the SDK sends
  both headers and the API rejects the request — this factory prefers the
  API key (explicit billing choice wins) and drops the auth token for that
  client to avoid the double-header rejection.
"""
from __future__ import annotations

import os

_OAUTH_BETA_HEADER = {"anthropic-beta": "oauth-2025-04-20"}


def anthropic_client():
    """Return an ``anthropic.Anthropic`` configured for this machine's auth."""

    import anthropic

    api_key = os.environ.get("ANTHROPIC_API_KEY")
    auth_token = (
        os.environ.get("ANTHROPIC_AUTH_TOKEN")
        or os.environ.get("CLAUDE_CODE_OAUTH_TOKEN")
        # RC-safe fallback: on the laptop the token is parked under this name so
        # it is NOT exported as ANTHROPIC_AUTH_TOKEN (which would disable Claude
        # Code Remote Control). See ~/.zshenv lines 24-27.
        or os.environ.get("ANTHROPIC_SDK_AUTH_TOKEN")
    )
    if api_key:
        # The SDK resolves ANTHROPIC_AUTH_TOKEN from env even when api_key is
        # passed explicitly (None means "resolve from env", so it cannot
        # suppress) — and sending both headers is rejected by the API.
        # Null the attribute post-construction to keep exactly one credential.
        client = anthropic.Anthropic(api_key=api_key)
        client.auth_token = None
        return client
    if auth_token:
        return anthropic.Anthropic(
            auth_token=auth_token, default_headers=dict(_OAUTH_BETA_HEADER)
        )
    # Neither set: construct the default client so the SDK raises its own
    # clear "could not resolve authentication" error at call time.
    return anthropic.Anthropic()
