"""claude-agent-sdk adapter — a shared SDK adapter, loaded by the
aw-orchestrator engine when an agent profile's `sdk.adapter` points here
(both .claude/agent.json and .kilocode/agent.json do). Adapters live in this
library keyed by SDK, not by agent: everything claude-agent-sdk-specific is
HERE, the engine ships no SDK code of its own, and each profile declares
which adapter drives its SDK.

Contract (see orchestrator.py `_run_sdk`):
    generate(request) -> str        # the model's final reply text
request keys:
    system            interpreter-assembled system block (standards + rules)
    user              interpreter-assembled user block (context + task)
    tools             comma-separated tool allowlist for the fresh session
    permission_mode   neutral mode: readonly | acceptEdits |
                      bypassPermissions | default
    model             model name or None
    sdk               the profile's full sdk block (for adapter options)
generate may be sync or async — the engine handles both.
"""
import os


def _dotenv_get(name):
    """Look up one key in ./.env then ~/.env (workspace wins); None if absent."""
    for env_path in (os.path.join(os.getcwd(), ".env"), os.path.expanduser("~/.env")):
        if not os.path.exists(env_path):
            continue
        with open(env_path, "r", encoding="utf-8") as fh:
            for line in fh:
                line = line.strip()
                if line and not line.startswith("#") and "=" in line:
                    k, v = line.split("=", 1)
                    if k.strip() == name:
                        return v.strip().strip("'\"")
    return None


# the SDK authenticates via ANTHROPIC_API_KEY (unless the claude CLI login is
# available); a value exported in the shell always wins — the .env lookup only
# fills the gap when nothing is exported
_key = _dotenv_get("ANTHROPIC_API_KEY")
if _key:
    os.environ.setdefault("ANTHROPIC_API_KEY", _key)

from claude_agent_sdk import ClaudeAgentOptions, query

# neutral permission modes → SDK modes ('readonly' is the workflow's notion,
# not an SDK mode — read-only is enforced by the tools allowlist)
_PERMISSION_MAP = {"acceptEdits": "acceptEdits",
                   "bypassPermissions": "bypassPermissions",
                   "default": "default", "readonly": "default"}


async def generate(request):
    allowed = [t.strip() for t in (request.get("tools") or "").split(",") if t.strip()]
    kwargs = dict(
        system_prompt=request["system"],
        allowed_tools=allowed,   # empty = payload-only; do not fall back to the SDK default set
        permission_mode=_PERMISSION_MAP.get(request["permission_mode"], "default"),
        setting_sources=[],   # isolation: no CLAUDE.md / settings / hooks
    )
    if request.get("model"):
        kwargs["model"] = request["model"]
    options = ClaudeAgentOptions(**kwargs)
    raw, texts = "", []
    async for msg in query(prompt=request["user"], options=options):
        r = getattr(msg, "result", None)
        if isinstance(r, str) and r:
            raw = r          # ResultMessage: the final reply text
        for blk in getattr(msg, "content", None) or []:
            t = getattr(blk, "text", None)
            if t:
                texts.append(t)
    return raw or "\n".join(texts)
