# tools/recents_tools.py — "Last N files I opened" for the Quick Panel.
#
# The list is sourced from the Swift client (NSDocumentController recent
# documents + Finder/Workspace heuristics) and POSTed to the backend via the
# authenticated `/recents` route. The tool just reads whatever the delegate
# has cached, so there is no HTTP loopback from the agent process and no
# risk of the tool scraping disk without TCC.
#
# Paths can be iCloud Drive placeholders (not downloaded). The tool reports
# that status so the agent can tell the user to open the file from Finder or
# let macOS pull it down before trying to read it.
from __future__ import annotations

import os
from typing import Any, Callable

from langchain_core.tools import tool

from tools._logging import _emit_input_status


# Provider is set by the backend at startup. When absent, the tool returns a
# clean, user-facing message instead of pretending to work.
_recents_provider: Callable[[int], list[dict[str, Any]]] | None = None


def set_recents_provider(provider: Callable[[int], list[dict[str, Any]]] | None) -> None:
    """Install the in-process provider that returns the cached recents list.

    The provider receives the requested limit and should return a list of
    dicts with at least ``path``; optional keys ``name``, ``last_opened`` and
    ``is_icloud_placeholder``.
    """
    global _recents_provider
    _recents_provider = provider


def _fmt_path(path: str) -> str:
    home = os.path.expanduser("~")
    if path.startswith(home):
        return "~" + path[len(home):]
    return path


@tool
def get_recent_files(limit: int = 5) -> str:
    """Return the most recently opened documents on this Mac.

    Use this when the user asks "what are the last files I opened" or
    similar recents-style questions from the Quick Panel. The list comes
    from the macOS client (NSDocumentController + Finder recents), not from
    scanning the disk — so it reflects what the user actually saw in menus
    like "File → Open Recent".

    Args:
        limit: Max rows to return (1–50). Defaults to 5.
    """
    _emit_input_status("Looking up recent files…")
    try:
        n = int(limit)
    except (TypeError, ValueError):
        n = 5
    n = max(1, min(50, n))

    provider = _recents_provider
    if provider is None:
        return (
            "Recent files are not available: the Mugi macOS app has not yet reported its "
            "recents list (open Mugi and bring up the Quick Panel once to seed it)."
        )

    try:
        items = list(provider(n)) or []
    except Exception as exc:
        return f"Could not read recents: {exc}"

    if not items:
        return "No recent documents yet. Open a file from Finder or an app's File → Open Recent to populate this list."

    rows: list[str] = []
    for item in items[:n]:
        if not isinstance(item, dict):
            continue
        path = (item.get("path") or "").strip()
        if not path:
            continue
        name = (item.get("name") or os.path.basename(path) or path).strip()
        when = (item.get("last_opened") or "").strip()
        suffix = ""
        if item.get("is_icloud_placeholder"):
            suffix = " (iCloud — open in Finder to download)"
        line = f"- {name} — {_fmt_path(path)}{suffix}"
        if when:
            line += f"  · {when}"
        rows.append(line)

    if not rows:
        return "No recent documents yet. Open a file from Finder or an app's File → Open Recent to populate this list."
    header = f"Most recent files ({len(rows)}):"
    return header + "\n" + "\n".join(rows)
