from __future__ import annotations

"""
JSONL DataSource 模块

提供基于 JSONL 文件的数据源实现，用于测试和本地开发。
"""

from pathlib import Path
from typing import TYPE_CHECKING

from ..type_registry import register_datasource_type
from .datasource import JsonlDataSource
from .handler import BaseJsonlHandler
from .path_utils import prepare_remote_jsonl_dir

if TYPE_CHECKING:
    from ...config.datasource_config import JsonlDataSourceConfig


def build_jsonl_datasource(
    config: JsonlDataSourceConfig,
    endpoint_name: str,
    *,
    project_root: Path | None = None,
):
    dir_path = Path(config.jsonl_dir)
    if endpoint_name == "remote":
        dir_path = prepare_remote_jsonl_dir(dir_path, project_root=project_root or Path.cwd())
    elif not dir_path.exists() or not dir_path.is_dir():
        raise FileNotFoundError(
            f"{endpoint_name}_datasource.jsonl_dir does not exist or is not a directory: {dir_path}"
        )
    return JsonlDataSource(dir_path, read_only=config.read_only)


def register(*, replace: bool = False) -> None:
    from ...config.datasource_config import JsonlDataSourceConfig

    register_datasource_type(
        "jsonl",
        config_model=JsonlDataSourceConfig,
        factory=build_jsonl_datasource,
        replace=replace,
    )

__all__ = [
    "JsonlDataSource",
    "BaseJsonlHandler",
    "build_jsonl_datasource",
    "prepare_remote_jsonl_dir",
    "register",
]
