"""Tests for CLI usage reporting to CXCoast API."""
from __future__ import annotations

import json
from pathlib import Path
from unittest.mock import AsyncMock, patch, MagicMock

import pytest


@pytest.mark.asyncio
async def test_report_usage_sends_correct_payload(tmp_path: Path) -> None:
    """Usage report sends correct payload to API."""
    config = {"apiUrl": "http://localhost:3000", "apiKey": "test-key"}
    config_path = tmp_path / ".cxcoast" / "config.json"
    config_path.parent.mkdir(parents=True)
    config_path.write_text(json.dumps(config))

    mock_client = AsyncMock()
    mock_client.__aenter__ = AsyncMock(return_value=mock_client)
    mock_client.__aexit__ = AsyncMock(return_value=False)
    mock_client.post = AsyncMock()

    from deepagents_cli.textual_adapter import _report_usage_to_api

    with patch.object(Path, "home", return_value=tmp_path), \
         patch("httpx.AsyncClient", return_value=mock_client):
        await _report_usage_to_api("anthropic", "claude-sonnet-4.5", 1500, 800)

    mock_client.post.assert_called_once()
    call_args = mock_client.post.call_args
    payload = call_args.kwargs.get("json") or call_args[1].get("json")
    assert payload["inputTokens"] == 1500
    assert payload["outputTokens"] == 800
    assert payload["channel"] == "cli"
    assert payload["provider"] == "anthropic"


@pytest.mark.asyncio
async def test_report_usage_silently_handles_errors() -> None:
    """Usage report does NOT raise on API failure."""
    from deepagents_cli.textual_adapter import _report_usage_to_api

    with patch.object(Path, "home", return_value=Path("/nonexistent")):
        # Should not raise — failures are silently caught
        await _report_usage_to_api("anthropic", "claude-sonnet-4.5", 100, 50)


@pytest.mark.asyncio
async def test_report_usage_skips_when_no_config(tmp_path: Path) -> None:
    """Usage report skips when config file doesn't exist."""
    from deepagents_cli.textual_adapter import _report_usage_to_api

    with patch.object(Path, "home", return_value=tmp_path):
        # No config file exists — should return silently without errors
        await _report_usage_to_api("anthropic", "claude-sonnet-4.5", 100, 50)
