"""Tests para load_claude_oauth_token."""

import json
import sys
import os
import time

sys.path.insert(0, os.path.dirname(__file__))

from load_claude_oauth_token import load_claude_oauth_token


def _write_creds(path, access_token, expires_at_ms, refresh_token="sk-ant-refresh-fake"):
    data = {
        "claudeAiOauth": {
            "accessToken": access_token,
            "refreshToken": refresh_token,
            "expiresAt": expires_at_ms,
        }
    }
    with open(path, "w") as f:
        json.dump(data, f)


def test_extrae_accessToken_de_un_credentials_fixture(tmp_path):
    creds = tmp_path / "credentials.json"
    _write_creds(str(creds), "sk-ant-oat-TEST123", expires_at_ms=int(time.time() * 1000) + 3_600_000)

    token = load_claude_oauth_token(credentials_path=str(creds), refresh_if_expired=False)

    assert token == "sk-ant-oat-TEST123"


def test_token_no_expirado_no_intenta_refresh(tmp_path, monkeypatch):
    creds = tmp_path / "credentials.json"
    # expiresAt 1 hora en el futuro
    future_ms = int(time.time() * 1000) + 3_600_000
    _write_creds(str(creds), "sk-ant-oat-FRESH", expires_at_ms=future_ms)

    refresh_called = {"n": 0}

    import load_claude_oauth_token as mod
    original_try_refresh = mod._try_refresh

    def fake_refresh(rt):
        refresh_called["n"] += 1
        return ""

    monkeypatch.setattr(mod, "_try_refresh", fake_refresh)

    token = load_claude_oauth_token(credentials_path=str(creds), refresh_if_expired=True)

    assert token == "sk-ant-oat-FRESH"
    assert refresh_called["n"] == 0


def test_token_expirado_con_refresh_if_expired_False_devuelve_token_igual(tmp_path):
    creds = tmp_path / "credentials.json"
    # expiresAt en el pasado
    past_ms = int(time.time() * 1000) - 3_600_000
    _write_creds(str(creds), "sk-ant-oat-EXPIRED", expires_at_ms=past_ms)

    token = load_claude_oauth_token(credentials_path=str(creds), refresh_if_expired=False)

    assert token == "sk-ant-oat-EXPIRED"


def test_token_expirado_refresh_falla_devuelve_token_y_warning_a_stderr(tmp_path, monkeypatch, capsys):
    creds = tmp_path / "credentials.json"
    past_ms = int(time.time() * 1000) - 3_600_000
    _write_creds(str(creds), "sk-ant-oat-OLD", expires_at_ms=past_ms, refresh_token="sk-ant-refresh-old")

    import load_claude_oauth_token as mod

    def fake_refresh_fails(rt):
        return ""  # simula fallo silencioso

    monkeypatch.setattr(mod, "_try_refresh", fake_refresh_fails)

    token = load_claude_oauth_token(credentials_path=str(creds), refresh_if_expired=True)

    assert token == "sk-ant-oat-OLD"
    captured = capsys.readouterr()
    assert "warning" in captured.err.lower()
    assert "expired" in captured.err.lower() or "refresh" in captured.err.lower()
