from __future__ import annotations

import pytest

from sync_state_machine.config import (
    PipelineRunConfig,
    JsonlDataSourceConfig,
    ApiDataSourceConfig,
    PersistConfig,
    LoggingConfig,
)


def _build_config(
    *,
    local_ids: list[str] | None = None,
    remote_ids: list[str] | None = None,
) -> PipelineRunConfig:
    return PipelineRunConfig(
        node_types=["project"],
        local_datasource=JsonlDataSourceConfig(
            type="jsonl",
            jsonl_dir="./filtered_datasource/datasource/filtered",
            handler_configs={"project": {"data_id_filter": local_ids or []}},
        ),
        remote_datasource=JsonlDataSourceConfig(
            type="jsonl",
            jsonl_dir="./remote_datasource/datasource",
            handler_configs={"project": {"data_id_filter": remote_ids or []}},
        ),
        strategies=[],
        persist=PersistConfig(db_path="./test_results/sync_state_machine/test.db"),
        logging=LoggingConfig(initialize=False),
    )


def test_pipeline_config_uses_handler_level_project_filters() -> None:
    cfg = _build_config(local_ids=["p_local"], remote_ids=["p_remote"])

    assert cfg.local_datasource.handler_configs["project"]["data_id_filter"] == ["p_local"]
    assert cfg.remote_datasource.handler_configs["project"]["data_id_filter"] == ["p_remote"]
    legacy_field_name = "_".join(("target", "project", "ids"))
    assert legacy_field_name not in type(cfg).model_fields


def test_api_datasource_allows_empty_handler_configs() -> None:
    cfg = ApiDataSourceConfig(
        type="api",
        api_base_url="https://example.com",
    )

    assert cfg.handler_configs == {}


def test_api_datasource_rate_limit_config_fields() -> None:
    cfg = ApiDataSourceConfig(
        type="api",
        api_base_url="https://example.com",
        handler_configs={"project": {"data_id_filter": ["p1"]}},
    )
    assert cfg.api_rate_limit_max_requests == 10
    assert cfg.api_rate_limit_window_seconds == 10.0

    overridden = ApiDataSourceConfig(
        type="api",
        api_base_url="https://example.com",
        api_rate_limit_max_requests=5,
        api_rate_limit_window_seconds=2.5,
        handler_configs={"project": {"data_id_filter": ["p1"]}},
    )
    assert overridden.api_rate_limit_max_requests == 5
    assert overridden.api_rate_limit_window_seconds == 2.5
