"""Helpers for accessing bundled documentation and workspace resources."""

from __future__ import annotations

import importlib.resources
import os
import shutil
import tempfile
from pathlib import Path

DOCS_RESOURCE_PACKAGE = "agent_flows_builder.resources"


def get_agent_workspace() -> Path:
    """Resolve the directory used to stage agent assets during execution."""
    if workspace := os.getenv("AGENT_FLOWS_WORKSPACE"):
        workspace_path = Path(workspace).resolve()
        workspace_path.mkdir(parents=True, exist_ok=True)
        return workspace_path

    return Path(tempfile.mkdtemp(prefix="agent-flows-"))


def _get_package_docs_directory() -> Path | None:
    """Return the packaged documentation directory if available."""
    try:
        with importlib.resources.as_file(
            importlib.resources.files(DOCS_RESOURCE_PACKAGE) / "docs"
        ) as docs_path:
            return docs_path if docs_path.exists() else None
    except Exception:
        return None


def ensure_docs_available(
    workspace: Path | str | None = None,
    *,
    force_update: bool = True,
) -> tuple[bool, Path]:
    """Ensure packaged documentation exists within the target workspace."""
    workspace_path = Path(workspace).resolve() if workspace else Path.cwd()
    docs_target = workspace_path / "docs"

    if not force_update and docs_target.exists() and docs_target.is_dir():
        return True, workspace_path

    package_docs = _get_package_docs_directory()
    if package_docs is None:
        return False, workspace_path

    try:
        if docs_target.exists():
            shutil.rmtree(docs_target)
        shutil.copytree(package_docs, docs_target, dirs_exist_ok=True)
        return True, workspace_path
    except Exception as exc:  # pragma: no cover - defensive guard
        print(f"Warning: Could not extract docs to workspace: {exc}")
        return False, workspace_path


def get_package_docs_path() -> Path | None:
    """Expose the path to bundled documentation for development workflows."""
    return _get_package_docs_directory()


__all__ = [
    "DOCS_RESOURCE_PACKAGE",
    "ensure_docs_available",
    "get_agent_workspace",
    "get_package_docs_path",
]
