"""Permission vocabulary and resolution.

The model is deliberately small: a flat set of named booleans, granted by an
instance-wide baseline and widened by group membership. Permissions are a union
across groups -- being in a second group can only ever grant more, never take
away. That is the behaviour people expect, and the alternative (a deny that
wins) makes "why can this user not do X" unanswerable without simulating every
group.

Administrators bypass the whole thing. There is no permission that can be
withheld from an admin, because an admin can grant it back to themselves in two
clicks; pretending otherwise would be theatre.

Model *access* is separate and lives in models_visible_to(): a permission says
what a user may do, model access says which models they may do it with.
"""

from __future__ import annotations

from dataclasses import dataclass

from sqlalchemy import select
from sqlalchemy.orm import Session as DBSession

from lembas.db.models import Connection, Model, User


@dataclass(frozen=True)
class PermissionDef:
    key: str
    label: str
    description: str
    default: bool
    group: str


# The order here is the order they render in the admin UI.
PERMISSION_DEFS: tuple[PermissionDef, ...] = (
    PermissionDef(
        "chat.create", "Start chats", "Create new conversations.", True, "Chat"
    ),
    PermissionDef(
        "chat.delete", "Delete chats", "Delete their own conversations.", True, "Chat"
    ),
    PermissionDef(
        "chat.system_prompt",
        "Set system prompts",
        "Give an individual chat its own system prompt.",
        True,
        "Chat",
    ),
    PermissionDef(
        "chat.params",
        "Adjust sampling",
        "Change temperature, top-p and similar per chat.",
        False,
        "Chat",
    ),
    PermissionDef(
        "chat.model_select",
        "Choose the model",
        "Switch a chat to a different model. Without this, chats use the default.",
        True,
        "Chat",
    ),
    PermissionDef(
        "folder.manage",
        "Manage folders",
        "Create, rename, nest and delete folders.",
        True,
        "Workspace",
    ),
    PermissionDef(
        "files.upload",
        "Attach files",
        "Attach images, PDFs and text files to a message. Images only reach "
        "models marked as having vision.",
        True,
        "Workspace",
    ),
    PermissionDef(
        "tools.web_search",
        "Search the web",
        "Let a model look things up while it answers. Only offered to models "
        "marked as supporting tools, and only when web search is configured.",
        True,
        "Chat",
    ),
    PermissionDef(
        "tools.custom",
        "Use custom tools",
        "Let a model call the HTTP tools an administrator has defined. Which "
        "ones depends on the groups each tool is restricted to.",
        True,
        "Chat",
    ),
    PermissionDef(
        "tools.mcp",
        "Use MCP servers",
        "Let a model call tools from the MCP servers an administrator has "
        "added. Which ones depends on the groups each server is restricted to.",
        True,
        "Chat",
    ),
    PermissionDef(
        "agent.ssh",
        "Save SSH connections",
        "Keep connection profiles for machines of their own. The credential is "
        "encrypted here, and whoever saves it decides which host it opens.",
        False,
        "Agent",
    ),
    PermissionDef(
        "tools.agent",
        "Run commands",
        "Let a model read files, write files and run commands on one of their "
        "SSH connections. What it may do without asking depends on the chat's "
        "mode. Nothing runs on this server.",
        False,
        "Agent",
    ),
    PermissionDef(
        "agent.terminal",
        "Open a terminal",
        "Open an interactive shell on one of their own SSH connections, from "
        "inside the chat. What they type there is theirs: the chat's mode "
        "governs the model, not the person at the keyboard.",
        False,
        "Agent",
    ),
    PermissionDef(
        "tools.ask",
        "Be asked questions",
        "Let a model stop mid-reply and ask you something, with answers to pick "
        "from or a box to write your own.",
        True,
        "Chat",
    ),
    PermissionDef(
        "audio.transcribe",
        "Dictate messages",
        "Speak a message instead of typing it. Needs a transcription endpoint.",
        True,
        "Audio",
    ),
    PermissionDef(
        "audio.listen",
        "Play replies aloud",
        "Have a reply read out. Needs a speech endpoint.",
        True,
        "Audio",
    ),
    PermissionDef(
        "library.use",
        "Use the library",
        "Keep knowledge documents, notes, memories and skills of their own.",
        True,
        "Library",
    ),
    PermissionDef(
        "library.share",
        "Share library items",
        "Give other people, or a group, access to their documents, notes and "
        "skills. Sharing grants reading only.",
        False,
        "Library",
    ),
    PermissionDef(
        "tools.knowledge",
        "Search their knowledge",
        "Let a model search the documents this user has collected.",
        True,
        "Library",
    ),
    PermissionDef(
        "tools.notes",
        "Read and write notes",
        "Let a model keep its own notes for this user, and read them back later.",
        True,
        "Library",
    ),
    PermissionDef(
        "tools.memory",
        "Remember things",
        "Let a model record short facts about this user, shown to it on every "
        "turn.",
        True,
        "Library",
    ),
    PermissionDef(
        "tools.skills",
        "Use and write skills",
        "Let a model follow saved instructions, and write new ones. Every "
        "change is recorded and can be rolled back.",
        True,
        "Library",
    ),
)

PERMISSION_KEYS = tuple(d.key for d in PERMISSION_DEFS)
DEFAULT_PERMISSIONS = {d.key: d.default for d in PERMISSION_DEFS}


def permission_groups() -> dict[str, list[PermissionDef]]:
    """Definitions bucketed by their UI section, preserving declaration order."""
    grouped: dict[str, list[PermissionDef]] = {}
    for definition in PERMISSION_DEFS:
        grouped.setdefault(definition.group, []).append(definition)
    return grouped


def baseline_permissions(db: DBSession) -> dict[str, bool]:
    """Instance-wide permissions for a user in no group at all."""
    from lembas.services import settings_store

    stored = settings_store.get(db, "default_permissions") or {}
    return {key: bool(stored.get(key, DEFAULT_PERMISSIONS[key])) for key in PERMISSION_KEYS}


def resolve(db: DBSession, user: User | None) -> dict[str, bool]:
    """Effective permissions for a user."""
    if user is None:
        return dict.fromkeys(PERMISSION_KEYS, False)
    if user.is_admin:
        return dict.fromkeys(PERMISSION_KEYS, True)

    effective = baseline_permissions(db)
    for group in user.groups:
        granted = group.permissions_json or {}
        for key in PERMISSION_KEYS:
            # Union: a group can only widen. Absent means "no opinion", not
            # "deny", so a group need only list what it adds.
            if granted.get(key):
                effective[key] = True
    return effective


def has(db: DBSession, user: User | None, key: str) -> bool:
    return resolve(db, user).get(key, False)


def models_visible_to(db: DBSession, user: User | None) -> list[Model]:
    """Models a user may start a chat with, in display order.

    A model is visible when it is enabled, its connection is enabled, and
    either it is public or the user belongs to one of its groups.
    """
    query = (
        select(Model)
        .join(Connection)
        .where(Model.enabled.is_(True), Connection.enabled.is_(True))
        .order_by(Model.position, Model.model_id)
    )
    candidates = list(db.scalars(query))

    if user is not None and user.is_admin:
        return candidates

    if user is None:
        return []

    member_of = {group.id for group in user.groups}
    return [
        model
        for model in candidates
        if model.public or member_of.intersection({g.id for g in model.groups})
    ]


def can_use_model(db: DBSession, user: User | None, model_id: str) -> bool:
    return any(model.model_id == model_id for model in models_visible_to(db, user))
