"""AgentLeisure Guard: ask before your agent runs a risky tool. Single file, standard library only. MIT.

    from agentleisure_guard import Guard
    guard = Guard(api_key="al_...")          # key from https://agentleisure.com/console

    @guard.tool("run_sql")
    def run_sql(query: str): ...

    run_sql(query="DROP TABLE users")         # waits for a human to approve; raises GuardDenied otherwise

Decisions: allow -> runs; deny -> raises GuardDenied; ask -> opens an approval request, prints the link
(or posts it to a Slack/Discord webhook via notify_url) and waits until a human approves or denies it.
Works with any framework: wrap the function you register as a tool (LangChain, CrewAI, OpenAI SDK, MCP...).
"""
import functools
import json
import time
import urllib.error
import urllib.request

__all__ = ["Guard", "GuardDenied"]
__version__ = "0.2.0"


class GuardDenied(Exception):
    def __init__(self, decision):
        super().__init__(decision.get("reason") or decision.get("decision") or "denied")
        self.decision = decision


class Guard:
    def __init__(self, api_key=None, base_url="https://agentleisure.com", notify_url=None,
                 timeout_minutes=30, poll_seconds=3, on_approval_needed=None, fail_closed=True):
        self.api_key = api_key
        self.base_url = base_url.rstrip("/")
        self.notify_url = notify_url
        self.timeout_minutes = timeout_minutes
        self.poll_seconds = poll_seconds
        self.on_approval_needed = on_approval_needed or (lambda link, d: print(f"[agentleisure] approval needed: {link}"))
        self.fail_closed = fail_closed

    def _request(self, method, path, body=None):
        headers = {"Content-Type": "application/json", "User-Agent": f"agentleisure-guard-py/{__version__}"}
        if self.api_key:
            headers["Authorization"] = f"Bearer {self.api_key}"
        data = json.dumps(body).encode() if body is not None else None
        req = urllib.request.Request(self.base_url + path, data=data, headers=headers, method=method)
        try:
            with urllib.request.urlopen(req, timeout=20) as res:
                return json.loads(res.read().decode() or "{}")
        except urllib.error.HTTPError as error:
            try:
                return json.loads(error.read().decode() or "{}")
            except ValueError:
                return {"error": f"http_{error.code}"}

    def check(self, tool, args=None, summary=None):
        """Return the raw decision dict without waiting."""
        body = {"tool": tool, "args": args if args is not None else {}, "request_approval": bool(self.api_key),
                "ttl_minutes": self.timeout_minutes}
        if summary:
            body["summary"] = summary[:300]
        if self.notify_url:
            body["notify_url"] = self.notify_url
        try:
            return self._request("POST", "/api/guard/check", body)
        except (urllib.error.URLError, TimeoutError, ValueError) as error:
            return {"decision": "deny" if self.fail_closed else "allow", "rule": "guard_unreachable", "reason": str(error)}

    def scan(self, text, source=None):
        """Check untrusted text (web page, issue, PR comment, tool result) for instructions aimed at an AI agent.
        Returns {"risk": "none"|"low"|"medium"|"high", "findings": [...], "advice": "..."}. On medium/high, treat it as data only."""
        body = {"text": str(text)[:100000]}
        if source:
            body["source"] = str(source)[:64]
        try:
            return self._request("POST", "/api/guard/scan", body)
        except (urllib.error.URLError, TimeoutError, ValueError) as error:
            return {"risk": "unknown", "findings": [], "error": str(error)}

    def require(self, tool, args=None, summary=None):
        """Block until the call may run. Raises GuardDenied if it may not."""
        decision = self.check(tool, args, summary)
        if decision.get("decision") == "allow":
            return decision
        if decision.get("decision") != "ask":
            raise GuardDenied(decision if decision.get("decision") else {**decision, "reason": decision.get("error", "guard error")})
        approval = decision.get("approval")
        if not approval:
            raise GuardDenied({**decision, "reason": f"{decision.get('reason')} (no approval: {decision.get('approval_error', 'set api_key')})"})
        self.on_approval_needed(approval["approve_url"], decision)
        deadline = time.time() + self.timeout_minutes * 60
        while time.time() < deadline:
            time.sleep(self.poll_seconds)
            status = self._request("GET", approval["status_url"]).get("status")
            if status == "approved":
                return decision
            if status in ("denied", "expired"):
                raise GuardDenied({**decision, "reason": f"human {status} the action"})
        raise GuardDenied({**decision, "reason": "approval timed out"})

    def tool(self, name=None):
        """Decorator: guard every call of the wrapped function."""
        def wrap(fn):
            tool_name = name or fn.__name__
            @functools.wraps(fn)
            def inner(*args, **kwargs):
                payload = {"args": [repr(a)[:2000] for a in args], **{k: v if isinstance(v, (str, int, float, bool, type(None))) else repr(v)[:2000] for k, v in kwargs.items()}}
                self.require(tool_name, payload)
                return fn(*args, **kwargs)
            return inner
        return wrap


if __name__ == "__main__":
    import sys
    g = Guard()
    tool = sys.argv[1] if len(sys.argv) > 1 else "run_sql"
    arg = sys.argv[2] if len(sys.argv) > 2 else "DROP TABLE users"
    print(json.dumps(g.check(tool, arg), indent=2))
