"""Tests for paginated site timeseries retrieval."""

from unittest.mock import Mock

from aceiot_models_cli.cli import cli
from aceiot_models_cli.commands.site import SiteTimeseriesCommand
from aceiot_models_cli.repl.context import ContextType, ReplContext


def test_sites_timeseries_command_uses_paginated_endpoint(
    runner,
    mock_load_config,
    mock_api_client_class,
    tmp_path,
):
    """The site timeseries export delegates pagination to the API client."""
    mock_api_client = mock_api_client_class.return_value
    mock_api_client.get_site_timeseries_paginated.return_value = {
        "point_samples": [
            {"name": "point1", "value": "70", "time": "2024-01-01T00:00:00Z"},
        ]
    }

    output_file = tmp_path / "timeseries.csv"
    result = runner.invoke(
        cli,
        [
            "sites",
            "timeseries",
            "demo-site",
            "--start",
            "2024-01-01T00:00:00Z",
            "--end",
            "2024-01-01T01:00:00Z",
            "--output-file",
            str(output_file),
            "--page-size",
            "3",
            "--raw-data",
        ],
    )

    assert result.exit_code == 0
    assert output_file.exists()
    mock_api_client.get_site_timeseries_paginated.assert_called_once_with(
        "demo-site",
        "2024-01-01T00:00:00Z",
        "2024-01-01T01:00:00Z",
        page_size=3,
        raw_data=True,
    )


def test_repl_site_timeseries_command_uses_paginated_endpoint(runner, tmp_path):
    """The context-aware REPL timeseries export delegates pagination to the API client."""
    mock_api_client = Mock()
    mock_api_client.get_site_timeseries_paginated.return_value = {
        "point_samples": [
            {"name": "point1", "value": "70", "time": "2024-01-01T00:00:00Z"},
        ]
    }

    repl_context = ReplContext()
    repl_context.enter_context(ContextType.SITE, "demo-site")
    command = SiteTimeseriesCommand(context=repl_context).get_click_command()

    output_file = tmp_path / "timeseries.csv"
    result = runner.invoke(
        command,
        [
            "--start",
            "2024-01-01T00:00:00Z",
            "--end",
            "2024-01-01T01:00:00Z",
            "--output-file",
            str(output_file),
            "--page-size",
            "3",
            "--raw-data",
        ],
        obj={"client": mock_api_client},
    )

    assert result.exit_code == 0
    assert output_file.exists()
    mock_api_client.get_site_timeseries_paginated.assert_called_once_with(
        "demo-site",
        "2024-01-01T00:00:00Z",
        "2024-01-01T01:00:00Z",
        page_size=3,
        raw_data=True,
    )
