from __future__ import annotations

import logging
from pathlib import Path


logger = logging.getLogger(__name__)


def prepare_remote_jsonl_dir(remote_dir: Path, *, project_root: Path) -> Path:
    project_root_path = project_root.resolve()
    resolved_remote_dir = remote_dir.resolve(strict=False)

    if resolved_remote_dir.exists():
        if not resolved_remote_dir.is_dir():
            raise FileNotFoundError(
                f"remote_datasource.jsonl_dir exists but is not a directory: {resolved_remote_dir}"
            )
        return resolved_remote_dir

    try:
        resolved_remote_dir.relative_to(project_root_path)
    except ValueError as exc:
        raise FileNotFoundError(
            "remote_datasource.jsonl_dir does not exist and auto-create is only allowed "
            f"under project root: {resolved_remote_dir} (project_root={project_root_path})"
        ) from exc

    resolved_remote_dir.mkdir(parents=True, exist_ok=True)
    logger.info("Created missing remote JSONL directory: %s", resolved_remote_dir)
    return resolved_remote_dir