#!/usr/bin/env python3
# Last updated: 2026-07-09
#
# bedrock_brad.py -- minimal bridge to AWS Bedrock via the Converse API.
# Mirrors gpt_brad.py's CLI so the debate skill's request-building code is
# unchanged: only the backend differs. The adversary model runs on Bedrock,
# reached through the default AWS credential chain (env vars / SSO on the
# sandbox account), so it costs nothing on a personal key.
#
# Subcommands:
#   model          Print the Bedrock model id that will be invoked (override or default).
#   ask            Read a JSON request on stdin, print the assistant's reply text.
#                  stdin JSON: {"system": "...", "messages": [{"role","content"}, ...],
#                              "model": "optional-override"}
#
# Model selection order (mirrors gpt_brad.py's override-first pattern):
#   1. the "model" field on the stdin request if present
#   2. else $BEDROCK_BRAD_MODEL if set
#   3. else the default: gpt-oss-120b -> openai.gpt-oss-120b-1:0
#
# Region: $BEDROCK_BRAD_REGION if set, else us-east-1 (where the sandbox text
# candidates invoke -- account 714293312392). The image path is us-west-2; do
# not conflate. This bridge is text-only.

import json
import os
import sys

try:
    import boto3
    from botocore.exceptions import (
        BotoCoreError,
        ClientError,
        NoCredentialsError,
    )
except ImportError:
    sys.exit(
        "boto3 is not importable. Install it with: pip install --user boto3"
    )

DEFAULT_MODEL_KEY = "gpt-oss-120b"
DEFAULT_REGION = "us-east-1"

# Short key -> the id to actually send to Converse. Mirrors invokeId() in the
# harness's lib/model-registry.mjs: models with no in-region on-demand endpoint
# carry their "us." cross-region inference profile. Kept in sync with that file;
# do not invent ids here.
BEDROCK_IDS = {
    "gpt-oss-120b": "openai.gpt-oss-120b-1:0",
    "gpt-oss-20b": "openai.gpt-oss-20b-1:0",
    "nova-lite": "amazon.nova-lite-v1:0",
    "nova-micro": "amazon.nova-micro-v1:0",
    "nova-2-lite": "us.amazon.nova-2-lite-v1:0",
    "llama3-3-70b": "us.meta.llama3-3-70b-instruct-v1:0",
    "claude-haiku-4-5": "us.anthropic.claude-haiku-4-5-20251001-v1:0",
}

# Auth/credential failure signatures that mean "re-auth the sandbox SSO session."
_AUTH_CODES = {
    "ExpiredTokenException",
    "ExpiredToken",
    "UnrecognizedClientException",
    "InvalidSignatureException",
    "AccessDeniedException",
    "UnauthorizedException",
}
_AUTH_HINTS = ("token", "credential", "sso", "expired", "security token")

_REAUTH_MSG = (
    "Bedrock call failed -- sandbox SSO creds look expired or unset; "
    "re-auth and retry."
)


def resolve_model(requested):
    """Resolve a requested model (short key, raw id, or blank) to a Bedrock id."""
    name = (requested or "").strip()
    if not name:
        name = os.environ.get("BEDROCK_BRAD_MODEL", "").strip()
    if not name:
        name = DEFAULT_MODEL_KEY
    if name in BEDROCK_IDS:
        return BEDROCK_IDS[name]
    # A raw Bedrock id (contains a "." provider prefix or a ":" version suffix)
    # passes through untouched. Anything else is an unknown short key -- fail
    # loudly rather than silently routing to the wrong model.
    if "." in name or ":" in name:
        return name
    sys.exit(
        f'bedrock_brad: unknown model "{name}". '
        f"Known keys: {', '.join(BEDROCK_IDS)} (or pass a raw Bedrock id)."
    )


def _max_tokens(model_id):
    # gpt-oss reasoning bills against output tokens, so give it headroom to
    # avoid truncating the answer behind chain-of-thought. Matches the registry.
    override = os.environ.get("BEDROCK_BRAD_MAX_TOKENS", "").strip()
    if override.isdigit():
        return int(override)
    return 8000 if "gpt-oss" in model_id else 4000


def _region():
    return os.environ.get("BEDROCK_BRAD_REGION", "").strip() or DEFAULT_REGION


def _extract_text(response):
    """Concatenate the {"text": ...} blocks from a Converse response, dropping
    any reasoningContent blocks so the caller never sees chain-of-thought."""
    try:
        blocks = response["output"]["message"]["content"]
    except (KeyError, TypeError):
        return ""
    chunks = [b["text"] for b in blocks if isinstance(b, dict) and "text" in b]
    return "".join(chunks).strip()


def _fail_auth_or_raise(err):
    """Print the re-auth message for credential failures; re-raise otherwise."""
    if isinstance(err, NoCredentialsError):
        sys.exit(_REAUTH_MSG)
    if isinstance(err, ClientError):
        code = err.response.get("Error", {}).get("Code", "")
        if code in _AUTH_CODES:
            sys.exit(_REAUTH_MSG)
    msg = str(err).lower()
    if any(h in msg for h in _AUTH_HINTS):
        sys.exit(_REAUTH_MSG)
    sys.exit(f"Bedrock call failed: {err}")


def ask():
    try:
        req = json.load(sys.stdin)
    except json.JSONDecodeError as e:
        sys.exit(f"Bad JSON on stdin: {e}")

    model_id = resolve_model(req.get("model"))
    messages = list(req.get("messages") or [])
    if not messages:
        sys.exit("No messages provided.")

    conv_messages = [
        {"role": m["role"], "content": [{"text": m["content"]}]}
        for m in messages
    ]
    kwargs = {
        "modelId": model_id,
        "messages": conv_messages,
        "inferenceConfig": {"maxTokens": _max_tokens(model_id)},
    }
    system = req.get("system")
    if system:
        kwargs["system"] = [{"text": system}]

    try:
        client = boto3.client("bedrock-runtime", region_name=_region())
        response = client.converse(**kwargs)
    except (ClientError, NoCredentialsError, BotoCoreError) as e:
        _fail_auth_or_raise(e)

    text = _extract_text(response)
    if not text:
        sys.exit("No text in response:\n" + json.dumps(response, indent=2, default=str))
    print(text)


def main():
    cmd = sys.argv[1] if len(sys.argv) > 1 else ""
    if cmd == "model":
        print(resolve_model(None))
    elif cmd == "ask":
        ask()
    else:
        sys.exit("Usage: bedrock_brad.py {model|ask}")


if __name__ == "__main__":
    main()
