"""Logic to merge profile presets with allow/also_allow/deny overrides."""

from __future__ import annotations

from peon_mcp.db import TOOL_POLICY_PROFILES
from peon_mcp.policies.schemas import ResolvedPolicy


def _split_tools(value: str) -> list[str]:
    """Split a comma-separated tool list, stripping whitespace and empty strings."""
    return [t.strip() for t in value.split(",") if t.strip()]


def resolve_policy(policy: dict) -> ResolvedPolicy:
    """Merge profile, allow, also_allow, and deny into a flat resolved policy.

    Resolution rules:
    - Start with the profile's tool list as the base set.
    - If ``allow`` is non-empty, it REPLACES the profile's list entirely.
    - ``also_allow`` is always additive (merged on top without replacing).
    - ``deny`` removes tools from the final set regardless of other fields.
    - Profile ``full`` means unrestricted (empty allowed_tools, is_unrestricted=True).
    """
    profile = policy["profile"]
    allow_raw = policy.get("allow", "")
    also_allow_raw = policy.get("also_allow", "")
    deny_raw = policy.get("deny", "")

    allow_tools = _split_tools(allow_raw)
    also_allow_tools = _split_tools(also_allow_raw)
    deny_tools = _split_tools(deny_raw)

    is_unrestricted = False

    if profile == "full" and not allow_tools:
        # Full profile with no explicit override = unrestricted
        is_unrestricted = True
        base: list[str] = []
    elif allow_tools:
        # Explicit allow list replaces profile
        base = list(allow_tools)
    else:
        # Use profile preset as base
        base = list(TOOL_POLICY_PROFILES.get(profile, []))

    # Add also_allow on top
    for tool in also_allow_tools:
        if tool not in base:
            base.append(tool)

    # Remove denied tools
    allowed = [t for t in base if t not in deny_tools]

    return ResolvedPolicy(
        policy_id=policy["id"],
        policy_name=policy["name"],
        profile=profile,
        allowed_tools=allowed,
        denied_tools=deny_tools,
        fs_workspace_only=bool(policy.get("fs_workspace_only", True)),
        exec_security=policy.get("exec_security", "allowlist"),
        exec_timeout_seconds=policy.get("exec_timeout_seconds", 300),
        is_unrestricted=is_unrestricted,
    )
