"""Registry of managed filesystem roots for path suggestion (lazy tool registration)."""

from __future__ import annotations

from dataclasses import dataclass


@dataclass(frozen=True)
class ManagedPathRoot:
    abs_path: str
    label: str


_REGISTRY: list[ManagedPathRoot] = []


def register_managed_root(abs_path: str, label: str) -> None:
    path = (abs_path or "").strip()
    if not path:
        return
    normalized = path.rstrip("/")
    for entry in _REGISTRY:
        if entry.abs_path.rstrip("/") == normalized:
            return
    _REGISTRY.append(ManagedPathRoot(abs_path=normalized, label=label))


def managed_roots() -> list[ManagedPathRoot]:
    return list(_REGISTRY)


def find_managed_root_for_path(abs_path: str) -> ManagedPathRoot | None:
    if not abs_path:
        return None
    try:
        import os

        target = os.path.realpath(os.path.expanduser(abs_path))
    except OSError:
        return None
    best: ManagedPathRoot | None = None
    best_len = -1
    for root in _REGISTRY:
        try:
            root_path = os.path.realpath(os.path.expanduser(root.abs_path))
        except OSError:
            continue
        prefix = root_path.rstrip(os.sep) + os.sep
        if target == root_path.rstrip(os.sep) or target.startswith(prefix):
            if len(root_path) > best_len:
                best = root
                best_len = len(root_path)
    return best
