"""Data acquisition — delegate to the coder agent for script generation.

The runner calls ``acquire_dataset_with_coder`` which asks the LLM to write
a download script. The script is executed in an isolated venv and the runner's
existing dependency installer handles packages automatically.

If a dataset already exists on disk, acquisition is skipped entirely.
"""
from __future__ import annotations

import logging
from pathlib import Path

logger = logging.getLogger(__name__)


def check_dataset_exists(
    dataset_path: str,
    workspace: Path | None = None,
    project_root: Path | None = None,
) -> tuple[bool, Path]:
    """Return (exists, resolved_path) for a dataset path.

    Searches in order: absolute path, workspace-relative, project-root-relative,
    then scans common subdirectories of the project root for a filename match.
    """
    raw = Path(dataset_path)

    # Absolute path
    if raw.is_absolute() and raw.exists():
        return True, raw

    # Relative to workspace
    if workspace:
        candidate = workspace / raw
        if candidate.exists():
            return True, candidate

    # Relative to project root
    if project_root:
        candidate = project_root / raw
        if candidate.exists():
            return True, candidate

        # Search common data directories for a filename match
        filename = raw.name
        search_dirs = ["data", "datasets", "input", "raw", "."]
        for subdir in search_dirs:
            search_root = project_root / subdir if subdir != "." else project_root
            if not search_root.is_dir():
                continue
            try:
                for item in search_root.rglob(filename):
                    if item.is_file():
                        logger.info("Found dataset at %s (searched from %s)", item, project_root)
                        return True, item
            except (PermissionError, OSError):
                pass

    # Fallback to the original logic
    target = (workspace / raw) if workspace and not raw.is_absolute() else raw
    return target.exists(), target
