"""
Kevros Governance Tools for CrewAI

Drop-in tools for any CrewAI agent.

Usage:
    from crewai_tools import get_governance_tools

    tools = get_governance_tools(api_key="kvrs_...")
    agent = Agent(role="Trader", tools=tools, ...)
"""

from __future__ import annotations

from typing import Any, Dict, List, Optional

import httpx

GATEWAY_URL = "https://governance.taskhawktech.com"
TIMEOUT = 30.0

try:
    from crewai.tools import BaseTool as CrewBaseTool
except ImportError:
    class CrewBaseTool:  # type: ignore[no-redef]
        name: str = ""
        description: str = ""
        def __init__(self, **kwargs: Any):
            for k, v in kwargs.items():
                setattr(self, k, v)


def _post(api_key: str, path: str, body: dict) -> str:
    headers = {"X-API-Key": api_key, "Content-Type": "application/json"}
    with httpx.Client(base_url=GATEWAY_URL, headers=headers, timeout=TIMEOUT) as c:
        resp = c.post(path, json=body)
        return resp.text


class GovernanceVerifyTool(CrewBaseTool):
    name: str = "Governance Verify"
    description: str = (
        "Verify an action against policy bounds. Input: JSON with action_type (string), "
        "action_payload (dict), agent_id (string), optional policy_context (dict). "
        "Returns ALLOW, CLAMP, or DENY with provenance hash. $0.01/call."
    )
    api_key: str = ""

    def _run(self, input_json: str) -> str:
        import json
        body = json.loads(input_json)
        return _post(self.api_key, "/governance/verify", body)


class GovernanceAttestTool(CrewBaseTool):
    name: str = "Governance Attest"
    description: str = (
        "Create a tamper-evident provenance record. Input: JSON with agent_id, "
        "action_description, action_payload. Returns hash-chained attestation. $0.02/call."
    )
    api_key: str = ""

    def _run(self, input_json: str) -> str:
        import json
        body = json.loads(input_json)
        return _post(self.api_key, "/governance/attest", body)


class GovernanceBindTool(CrewBaseTool):
    name: str = "Governance Bind Intent"
    description: str = (
        "Declare intent and bind to command. Input: JSON with agent_id, intent_type, "
        "intent_description, command_payload. Returns binding proof. $0.02/call."
    )
    api_key: str = ""

    def _run(self, input_json: str) -> str:
        import json
        body = json.loads(input_json)
        body.setdefault("intent_source", "AI_PLANNER")
        return _post(self.api_key, "/governance/bind", body)


def get_governance_tools(api_key: str) -> List[CrewBaseTool]:
    """Get all Kevros governance tools for a CrewAI agent."""
    return [
        GovernanceVerifyTool(api_key=api_key),
        GovernanceAttestTool(api_key=api_key),
        GovernanceBindTool(api_key=api_key),
    ]
