from __future__ import annotations

import os
from pathlib import Path

from aicd.config import PathPolicyConfig


class PathPolicy:
    def __init__(self, cfg: PathPolicyConfig) -> None:
        self._cfg = cfg
        self._roots = [_expand_root(r) for r in cfg.allowed_roots]
        # 当前 AI 工作区（随 /work 变化）；full_disk=false 时始终允许该目录下读写
        self._workspace_root: Path | None = None

    def set_workspace_root(self, root: Path | None) -> None:
        """与 ToolRouter 主工作目录同步；解决 allowed_roots 里 "." 只在启动时展开的问题。"""
        self._workspace_root = root.resolve() if root is not None else None

    def resolve(self, path_str: str, cwd: Path | None = None) -> Path:
        base = cwd or Path.cwd()
        p = Path(path_str).expanduser()
        if not p.is_absolute():
            p = (base / p).resolve()
        else:
            p = p.resolve()
        return p

    def check_allowed(self, path: Path) -> None:
        if self._cfg.full_disk:
            return
        path = path.resolve()
        wr = self._workspace_root
        if wr is not None:
            try:
                path.relative_to(wr)
                return
            except ValueError:
                pass
        for root in self._roots:
            try:
                path.relative_to(root)
                return
            except ValueError:
                continue
        raise PermissionError(f"Path not under allowed_roots: {path}")


def _expand_root(spec: str) -> Path:
    s = os.path.expandvars(spec)
    return Path(s).expanduser().resolve()
