"""Permission system — 3-tier confirmation for tool execution."""

from __future__ import annotations

import json
from pathlib import Path

from tsumugi.tools.base import PermissionLevel
from tsumugi.ui import display

_PERMISSIONS_FILE = Path.home() / ".tsumugi" / "permissions.json"


class PermissionManager:
    """Manages tool execution permissions with session and persistent overrides."""

    def __init__(self) -> None:
        # Tools that are always allowed for this session
        self._always_allowed: set[str] = set()
        # Tools that are persistently allowed
        self._persistent_allowed: set[str] = set()
        self._load_persistent()

    def check(
        self, tool_name: str, permission: PermissionLevel, args_summary: str
    ) -> bool:
        """Check if a tool execution is allowed.

        Returns True if allowed, False if denied.
        READ tools are always auto-allowed.
        WRITE/EXECUTE tools require user confirmation unless always-allowed.
        """
        if permission == PermissionLevel.READ:
            return True

        if tool_name in self._always_allowed:
            return True

        if tool_name in self._persistent_allowed:
            return True

        return self._ask_permission(tool_name, permission, args_summary)

    def _ask_permission(
        self, tool_name: str, permission: PermissionLevel, args_summary: str
    ) -> bool:
        """Prompt user for permission."""
        level_label = (
            "[yellow]WRITE[/yellow]"
            if permission == PermissionLevel.WRITE
            else "[red]EXECUTE[/red]"
        )

        display.console.print()
        display.console.print(
            f"  {level_label} permission required for [bold cyan]{tool_name}[/bold cyan]"
        )
        if args_summary:
            display.console.print(f"  [dim]{args_summary}[/dim]")
        display.console.print()
        display.console.print(
            "  [dim](y)es / (n)o / (a)lways this session / (p)ersist forever[/dim]"
        )

        while True:
            try:
                choice = input("  > ").strip().lower()
            except (EOFError, KeyboardInterrupt):
                return False

            if choice in ("y", "yes"):
                return True
            elif choice in ("n", "no"):
                return False
            elif choice in ("a", "always"):
                self._always_allowed.add(tool_name)
                display.console.print(
                    f"  [green]{tool_name} をこのセッションで常に許可します[/green]"
                )
                return True
            elif choice in ("p", "persist"):
                self._persistent_allowed.add(tool_name)
                self._save_persistent()
                display.console.print(
                    f"  [green]{tool_name} を永続的に許可しました[/green]"
                )
                return True
            else:
                display.console.print("  [dim]y / n / a / p を入力してください[/dim]")

    def _load_persistent(self) -> None:
        """Load persistent permissions from disk."""
        if _PERMISSIONS_FILE.exists():
            try:
                data = json.loads(_PERMISSIONS_FILE.read_text(encoding="utf-8"))
                self._persistent_allowed = set(data.get("allowed_tools", []))
            except (json.JSONDecodeError, OSError):
                pass

    def _save_persistent(self) -> None:
        """Save persistent permissions to disk."""
        _PERMISSIONS_FILE.parent.mkdir(parents=True, exist_ok=True)
        data = {"allowed_tools": sorted(self._persistent_allowed)}
        _PERMISSIONS_FILE.write_text(
            json.dumps(data, indent=2, ensure_ascii=False),
            encoding="utf-8",
        )
