"""
SealVera Python SDK — AI Decision Audit Logging

Quick start:
    import sealvera

    sealvera.init(api_key="sv_...", agent="my-agent")

    # Manual log
    sealvera.log(
        action="evaluate_transaction",
        decision="APPROVED",
        input={"tx_id": "123", "amount": 150},
        output={"risk_score": 0.12},
        reasoning=[{"factor": "risk", "value": "0.12", "signal": "safe", "explanation": "Below threshold"}]
    )

    # LangChain — drop-in callback handler
    from sealvera.callbacks import SealVeraCallbackHandler
    handler = SealVeraCallbackHandler()
    llm = ChatOpenAI(callbacks=[handler])

    # Decorator — wraps any function
    @sealvera.audit(action="process_payment")
    def process_payment(amount, customer_id):
        ...

    # Context manager — group decisions into one trace
    with sealvera.trace("pipeline-run-001") as t:
        result = my_agent.run(task)
        t.log(action="agent_run", decision="COMPLETED", output={"result": result})
"""

from .client import SealVeraClient, _default_client
from .decorators import audit
from .trace import TraceContext

import os
import functools

# Auto-activate zero-touch intercept if SEALVERA_AUTOLOAD=1
if os.environ.get("SEALVERA_AUTOLOAD") == "1":
    from . import autoload as _autoload
    _autoload.activate()

# ── Public API ─────────────────────────────────────────────────────────────────

def init(
    api_key: str = None,
    agent: str = None,
    endpoint: str = None,
    auto_flush: bool = True,
    timeout: float = 5.0,
):
    """
    Configure the default SealVera client.

    Args:
        api_key:    Your SealVera API key (sv_...). Falls back to SEALVERA_API_KEY env var.
        agent:      Agent/system name shown on the dashboard. Falls back to SEALVERA_AGENT env var.
        endpoint:   SealVera server URL. Defaults to https://app.sealvera.com.
        auto_flush: Flush pending logs on process exit (default True).
        timeout:    HTTP request timeout in seconds (default 5.0).
    """
    _default_client.configure(
        api_key=api_key,
        agent=agent,
        endpoint=endpoint,
        auto_flush=auto_flush,
        timeout=timeout,
    )


def log(
    action: str,
    decision: str,
    input: dict = None,
    output: dict = None,
    reasoning: list = None,
    agent: str = None,
    trace_id: str = None,
    trace_name: str = None,
    model: str = None,
    timestamp: str = None,
    id: str = None,
    blocking: bool = False,
) -> dict:
    """
    Log a decision to SealVera.

    Decision vocabulary:
        Task:  COMPLETED  RESPONDED  FAILED  ERROR  ESCALATED  SKIPPED  PARTIAL
        Tests: PASSED  FAILED  SKIPPED  ERROR
        Gates: APPROVED  REJECTED  FLAGGED

    Args:
        action:     What the agent did (e.g. "evaluate_transaction")
        decision:   Outcome from vocabulary above
        input:      Input data dict
        output:     Output/result dict
        reasoning:  List of {factor, value, signal, explanation} dicts
        agent:      Override agent name for this log entry
        trace_id:   Group related decisions into one trace
        trace_name: Human-readable trace label
        model:      Model used (e.g. "gpt-4o", "claude-3-5-sonnet")
        blocking:   If True, wait for server response (default False — fire and forget)

    Returns:
        {"ok": True, "id": "uuid"} or {} if non-blocking
    """
    return _default_client.log(
        action=action,
        decision=decision,
        input=input or {},
        output=output or {},
        reasoning=reasoning or [],
        agent=agent,
        trace_id=trace_id,
        trace_name=trace_name,
        model=model,
        timestamp=timestamp,
        id=id,
        blocking=blocking,
    )


def trace(trace_id: str, trace_name: str = None) -> "TraceContext":
    """
    Context manager — group related decisions into one audit trace.

    Usage:
        with sealvera.trace("pipeline-001", "Document Pipeline") as t:
            result = agent.run(task)
            t.log(action="agent_run", decision="COMPLETED", output={"result": result})
    """
    return TraceContext(_default_client, trace_id=trace_id, trace_name=trace_name)


def flush():
    """Wait for all pending async log requests to complete."""
    _default_client.flush()


def audit(action: str = None, agent: str = None, decision_fn=None):
    """
    Decorator — automatically logs the result of any function call.

    Usage:
        @sealvera.audit(action="process_payment")
        def process_payment(amount, customer_id):
            return {"status": "ok"}

        # decision_fn maps return value to a decision string:
        @sealvera.audit(action="classify", decision_fn=lambda r: "APPROVED" if r["safe"] else "REJECTED")
        def classify(text):
            return {"safe": True}
    """
    from .decorators import audit as _audit
    return _audit(action=action, agent=agent, decision_fn=decision_fn, client=_default_client)


__all__ = ["init", "log", "trace", "flush", "audit", "SealVeraClient"]
__version__ = "0.1.0"
