"""API client methods for tool policies."""

from __future__ import annotations

from typing import Any

from peon_mcp.common.base_client import BaseAPIClient


class PolicyClient(BaseAPIClient):
    """Tool policy API client methods."""

    async def create_policy(
        self,
        project_id: str,
        name: str,
        profile: str = "coding",
        allow: str = "",
        also_allow: str = "",
        deny: str = "",
        fs_workspace_only: bool = True,
        exec_security: str = "allowlist",
        exec_timeout_seconds: int = 300,
        is_default: bool = False,
    ) -> dict | str:
        body: dict[str, Any] = {
            "project_id": project_id,
            "name": name,
            "profile": profile,
            "allow": allow,
            "also_allow": also_allow,
            "deny": deny,
            "fs_workspace_only": fs_workspace_only,
            "exec_security": exec_security,
            "exec_timeout_seconds": exec_timeout_seconds,
            "is_default": is_default,
        }
        return await self._request("POST", "/api/policies", json=body)

    async def list_policies(self, project_id: str) -> list[dict] | str:
        return await self._paginate_all("/api/policies", params={"project_id": project_id})

    async def get_policy(self, policy_id: int) -> dict | str:
        return await self._request("GET", f"/api/policies/{policy_id}")

    async def update_policy(
        self,
        policy_id: int,
        name: str | None = None,
        profile: str | None = None,
        allow: str | None = None,
        also_allow: str | None = None,
        deny: str | None = None,
        fs_workspace_only: bool | None = None,
        exec_security: str | None = None,
        exec_timeout_seconds: int | None = None,
        is_default: bool | None = None,
    ) -> dict | str:
        body: dict[str, Any] = {}
        if name is not None:
            body["name"] = name
        if profile is not None:
            body["profile"] = profile
        if allow is not None:
            body["allow"] = allow
        if also_allow is not None:
            body["also_allow"] = also_allow
        if deny is not None:
            body["deny"] = deny
        if fs_workspace_only is not None:
            body["fs_workspace_only"] = fs_workspace_only
        if exec_security is not None:
            body["exec_security"] = exec_security
        if exec_timeout_seconds is not None:
            body["exec_timeout_seconds"] = exec_timeout_seconds
        if is_default is not None:
            body["is_default"] = is_default
        return await self._request("PUT", f"/api/policies/{policy_id}", json=body)

    async def delete_policy(self, policy_id: int) -> dict | str:
        return await self._request("DELETE", f"/api/policies/{policy_id}")

    async def resolve_policy(self, policy_id: int) -> dict | str:
        return await self._request("GET", f"/api/policies/{policy_id}/resolve")
