"""Vault path resolution — maps logical paths to physical locations.

Physical layout:
    root_dir/
    ├── agntspace-inbox/          ← drop zone
    ├── agntspace-journal/        ← user journal + agent observations
    ├── agntspace-knowledge/      ← knowledge bases
    ├── agntspace-projects/       ← projects + tasks + goals
    ├── agntspace/                ← agent internals
    │   ├── system/               ← identity, skills, agents, security
    │   └── memory/               ← MEMORY.md, graph, summaries
    └── user's files/             ← untouched

Logical paths used in code:
    "knowledge/..."               → root_dir/agntspace-knowledge/...
    "journal/..."                 → root_dir/agntspace-journal/...
    "inbox/..."                   → root_dir/agntspace-inbox/...
    "projects/..."                → root_dir/agntspace-projects/...
    "system/..."                  → root_dir/agntspace/system/...
    "memory/..."                  → root_dir/agntspace/memory/...
    anything else                 → root_dir/agntspace/...
"""

from __future__ import annotations

from pathlib import Path


def norm_path(p: str | Path) -> str:
    """Normalize a path to forward-slash form for stable cross-platform comparisons.

    Use this wherever the code needs to do substring / startswith / equality
    checks on paths produced by pathlib on Windows (which uses backslashes).
    Do NOT use it for filesystem operations — pass ``Path`` objects to those.
    """
    return str(p).replace("\\", "/")


class VaultPaths:
    """Maps logical vault-relative paths to physical filesystem paths."""

    def __init__(self, root_dir: Path) -> None:
        self.root_dir = root_dir
        self.internals_dir = root_dir / "agntspace"

        # Pairs: (logical_prefix, physical_base).
        self._prefix_map: list[tuple[str, Path]] = [
            ("knowledge/",  root_dir / "agntspace-knowledge"),
            ("journal/",    root_dir / "agntspace-journal"),
            ("inbox/",      root_dir / "agntspace-inbox"),
            ("projects/",   root_dir / "agntspace-projects"),
            ("goals/",      root_dir / "agntspace-goals"),
            ("finance/",    root_dir / "agntspace-finance"),
            ("system/",     root_dir / "agntspace" / "system"),
            ("memory/",     root_dir / "agntspace" / "memory"),
        ]

    def resolve(self, relative_path: str) -> Path:
        """Convert a logical vault-relative path to a physical path."""
        normalized = relative_path.replace("\\", "/")
        for prefix, base in self._prefix_map:
            if normalized.startswith(prefix):
                remainder = normalized[len(prefix):]
                return base / remainder if remainder else base
        # Bare names without slash (e.g., "inbox", "knowledge")
        with_slash = normalized + "/"
        for prefix, base in self._prefix_map:
            if with_slash == prefix:
                return base
        # Default: everything else inside agntspace/
        return self.internals_dir / normalized

    def to_logical(self, physical_path: Path) -> str:
        """Convert a physical path back to a logical vault-relative path."""
        try:
            physical = physical_path.resolve()
        except (OSError, ValueError):
            physical = physical_path

        reverse_map: list[tuple[Path, str]] = [
            (self.root_dir / "agntspace-knowledge", "knowledge/"),
            (self.root_dir / "agntspace-journal",   "journal/"),
            (self.root_dir / "agntspace-inbox",     "inbox/"),
            (self.root_dir / "agntspace-projects",  "projects/"),
            (self.root_dir / "agntspace-goals",     "goals/"),
            (self.root_dir / "agntspace-finance",   "finance/"),
            (self.root_dir / "agntspace" / "system", "system/"),
            (self.root_dir / "agntspace" / "memory", "memory/"),
        ]
        for base, prefix in reverse_map:
            try:
                resolved_base = base.resolve()
                rel = physical.relative_to(resolved_base)
                return prefix + str(rel).replace("\\", "/")
            except ValueError:
                continue

        # Fall back to internals
        try:
            rel = physical.relative_to(self.internals_dir.resolve())
            return str(rel).replace("\\", "/")
        except ValueError:
            pass

        # Last resort: relative to root
        try:
            rel = physical.relative_to(self.root_dir.resolve())
            return str(rel).replace("\\", "/")
        except ValueError:
            return str(physical)

    def all_content_roots(self) -> list[Path]:
        """Return all physical directories that contain vault content."""
        roots = [
            self.root_dir / "agntspace-inbox",
            self.root_dir / "agntspace-journal",
            self.root_dir / "agntspace-knowledge",
            self.root_dir / "agntspace-projects",
            self.root_dir / "agntspace-goals",
            self.root_dir / "agntspace-finance",
            self.internals_dir / "system",
            self.internals_dir / "memory",
        ]
        return [r for r in roots if r.is_dir()]

    def all_init_dirs(self) -> list[Path]:
        """Return all directories that should be created on init."""
        root = self.root_dir
        internal = self.internals_dir
        return [
            root / "agntspace-inbox",
            root / "agntspace-journal",
            root / "agntspace-knowledge",
            root / "agntspace-projects",
            internal / "system" / "identity",
            internal / "system" / "agents",
            internal / "system" / "skills",
            internal / "system" / "security",
            internal / "system" / "logs",
            internal / "system" / "logs" / "simulation",
            internal / "memory",
            internal / "memory" / "pending",
            internal / "memory" / "graph",
            internal / "memory" / "summaries",
        ]
