"""
Marco DVCS - Public Python SDK
==============================
Import marco directly inside your training scripts to use version tags
instead of file paths.

    import marco
    data_path = marco.get_data("v1-raw")        # resolves to preprocessed.tsv
    marco.save_results("v1-raw", "results.txt") # stores back into the version
"""

__version__ = "0.1.67"

from pathlib import Path


def _find_repo(start=None):
    """Walk up from start (or cwd) to find the directory containing .marco/"""
    current = Path(start).resolve() if start else Path.cwd().resolve()
    for parent in [current] + list(current.parents):
        if (parent / '.marco').is_dir():
            return parent
    raise FileNotFoundError(
        "No .marco repository found. Run 'marco init' first in your project directory."
    )


def get_data(version, repo_path=None):
    """
    Resolve a Marco version tag or hash prefix and return the path to its
    preprocessed.tsv file — pass the result directly to pandas or sklearn.

    Parameters
    ----------
    version   : str   Version tag (e.g. 'v1-raw') or hash prefix
    repo_path : str   Optional project root path (auto-detected if omitted)

    Returns
    -------
    pathlib.Path  Absolute path to preprocessed.tsv

    Example
    -------
    >>> import marco, pandas as pd
    >>> df = pd.read_csv(marco.get_data("v1-raw"), sep="\\t")
    """
    from marco.core.repository import resolve_version
    rp = Path(repo_path) if repo_path else _find_repo()
    vid = resolve_version(version, rp)
    tsv = rp / '.marco' / 'versions' / vid / 'preprocessed.tsv'
    if not tsv.exists():
        raise FileNotFoundError(
            f"preprocessed.tsv not found for version '{version}' ({vid[:12]}). "
            "Run 'marco upload' to generate it."
        )
    return tsv


def save_results(version, results_path, repo_path=None):
    """
    Save a training results file into a Marco version directory —
    replaces the need for 'marco attach-results' in the CLI.

    Parameters
    ----------
    version      : str   Version tag or hash prefix (e.g. 'v1-raw')
    results_path : str   Path to your results file (e.g. 'results.txt')
    repo_path    : str   Optional project root path (auto-detected if omitted)

    Returns
    -------
    pathlib.Path  Path where the file was stored inside .marco/versions/

    Example
    -------
    >>> import marco
    >>> marco.save_results("v1-raw", "training_results.txt")
    """
    from marco.core.repository import attach_results
    rp = Path(repo_path) if repo_path else _find_repo()
    _vid, dest = attach_results(version, results_path, rp)
    return dest
