"""CLI command for exporting the bundled LLM skill."""

from __future__ import annotations

import shutil
from importlib.metadata import metadata
from importlib.resources import files as pkg_files
from pathlib import Path


def _get_dist_name() -> str:
    """Derive the PyPI distribution name from this package's installed metadata."""
    package_name = __package__.rsplit(".", 1)[0]  # "qrm"
    try:
        from importlib.metadata import packages_distributions

        dist_map = packages_distributions()
        dists = dist_map.get(package_name, [])
        if dists:
            return dists[0]
    except ImportError:
        pass
    for prefix in (f"lr-{package_name}", package_name):
        try:
            metadata(prefix)
            return prefix
        except Exception:
            continue
    return package_name


def _get_version() -> str:
    """Return the installed version of this distribution."""
    try:
        return metadata(_get_dist_name())["Version"]
    except Exception:
        return "unknown"


_PACKAGE_ROOT = __package__.rsplit(".", 1)[0]  # "qrm"
_LLM_PACKAGE = f"{_PACKAGE_ROOT}.llm"  # "qrm.llm"
_SKILL_NAME = _get_dist_name()  # "lr-qrm"


def _skill_source_dir() -> Path:
    """Return the path to the bundled llm/ directory inside the installed package."""
    return Path(str(pkg_files(_LLM_PACKAGE)))


def _copy_skill(dest_dir: Path) -> Path:
    """Copy the skill folder to dest_dir/<skill-name>/ and return the path."""
    src = _skill_source_dir()
    target = dest_dir / _SKILL_NAME
    if target.exists():
        shutil.rmtree(target)
    shutil.copytree(
        src,
        target,
        ignore=shutil.ignore_patterns("__pycache__", "*.pyc", "__init__.py"),
    )
    return target


__all__ = ["_copy_skill", "_skill_source_dir", "_get_version", "_SKILL_NAME"]
