#!/usr/bin/env python3
"""Measure first visible output, completion time and task correctness on Bedrock."""

import argparse
from datetime import datetime, timezone
import http.client
import json
import os
import re
from statistics import median
import time

from cases import CASES


SYSTEM = "Follow the user request exactly. When asked for JSON, return only JSON, with no markdown or commentary."
MODELS = ("global.amazon.ergo-1.0", "us.amazon.ergo-1.0")
RATES = {MODELS[0]: (1.00, 3.00, 0.03), MODELS[1]: (1.10, 3.30, 0.033)}
PATH = "/openai/v1/chat/completions"
MAX_COMPLETION_TOKENS = 8192


class IncompleteStream(Exception):
    pass


def events(stream):
    data = []
    for line in stream:
        line = line.rstrip(b"\r\n")
        if not line and data:
            yield b"\n".join(data)
            data.clear()
        elif line.startswith(b"data:"):
            data.append(line[5:].lstrip(b" "))
    if data:
        yield b"\n".join(data)


def parse_stream(stream, elapsed):
    text_parts = []
    calls = {}
    first_visible = None
    finish = None
    usage = None
    response_model = None
    for event in events(stream):
        if event == b"[DONE]":
            break
        chunk = json.loads(event)
        if chunk.get("error"):
            raise IncompleteStream("Bedrock returned an error in the event stream")
        response_model = chunk.get("model") or response_model
        usage = chunk.get("usage") or usage
        for choice in chunk.get("choices", []):
            finish = choice.get("finish_reason") or finish
            delta = choice.get("delta") or {}
            content = delta.get("content")
            tool_calls = delta.get("tool_calls") or []
            if first_visible is None and (content or tool_calls):
                first_visible = elapsed()
            if content:
                text_parts.append(content)
            for tool_call in tool_calls:
                call = calls.setdefault(tool_call["index"], {"name": "", "arguments": ""})
                function = tool_call.get("function") or {}
                call["name"] += function.get("name") or ""
                call["arguments"] += function.get("arguments") or ""
    else:
        raise IncompleteStream("Stream ended before the completion marker")
    return {
        "first_visible_output_s": first_visible,
        "total_s": elapsed(),
        "finish_reason": finish,
        "response_model": response_model,
        "text": "".join(text_parts),
        "tool_calls": [calls[index] for index in sorted(calls)],
        "usage": usage,
    }


def score(case, result):
    try:
        if case.get("tools"):
            if result["finish_reason"] != "tool_calls" or result["text"].strip():
                return False
            actual = [
                {"name": call["name"], "arguments": json.loads(call["arguments"])}
                for call in result["tool_calls"]
            ]
        else:
            if result["finish_reason"] != "stop" or result["tool_calls"]:
                return False
            actual = json.loads(result["text"])
    except json.JSONDecodeError:
        return False
    return json.dumps(actual, sort_keys=True) == json.dumps(case["expected"], sort_keys=True)


def cost_usd(model, usage):
    if not usage or "prompt_tokens" not in usage or "completion_tokens" not in usage:
        return None
    input_rate, output_rate, cached_rate = RATES[model]
    prompt = usage["prompt_tokens"]
    completion = usage["completion_tokens"]
    cached = (usage.get("prompt_tokens_details") or {}).get("cached_tokens") or 0
    return round(((prompt - cached) * input_rate + cached * cached_rate + completion * output_rate) / 1_000_000, 9)


def benchmark_case(case, region, model, effort, token):
    payload = {
        "model": model,
        "messages": [{"role": "system", "content": SYSTEM}, {"role": "user", "content": case["prompt"]}],
        "reasoning_effort": effort,
        "max_completion_tokens": MAX_COMPLETION_TOKENS,
        "stream": True,
        "stream_options": {"include_usage": True},
    }
    if case.get("tools"):
        payload["tools"] = case["tools"]
    connection = http.client.HTTPSConnection(f"bedrock-runtime.{region}.amazonaws.com", timeout=120)
    started = time.perf_counter()

    def elapsed():
        return round(time.perf_counter() - started, 6)

    try:
        connection.request("POST", PATH, body=json.dumps(payload).encode("utf-8"), headers={
            "Authorization": f"Bearer {token}",
            "Content-Type": "application/json",
            "Accept": "text/event-stream",
        })
        with connection.getresponse() as response:
            if response.status != 200:
                return {
                    "http_status": response.status,
                    "error": "Bedrock rejected the request",
                    "total_s": elapsed(),
                }
            if "text/event-stream" not in response.headers.get("Content-Type", ""):
                raise IncompleteStream("Bedrock did not return an event stream")
            result = parse_stream(response, elapsed)
    except IncompleteStream as exc:
        return {"error": str(exc), "total_s": elapsed()}
    except (OSError, http.client.HTTPException, ValueError, TypeError, KeyError) as exc:
        return {"error": type(exc).__name__, "total_s": elapsed()}
    finally:
        connection.close()

    result["passed"] = score(case, result)
    result["estimated_usd"] = cost_usd(model, result["usage"])
    return result


def summarize(results):
    completed = [row for row in results if "passed" in row]
    first_visible = [row["first_visible_output_s"] for row in completed if row["first_visible_output_s"] is not None]
    costs = [row["estimated_usd"] for row in completed if row["estimated_usd"] is not None]
    return {
        "attempted": len(results),
        "completed": len(completed),
        "passed": sum(row["passed"] for row in completed),
        "errors": len(results) - len(completed),
        "median_first_visible_output_s": median(first_visible) if first_visible else None,
        "median_total_s": median(row["total_s"] for row in completed) if completed else None,
        "estimated_usd_for_reported_usage": round(sum(costs), 9) if costs else None,
        "requests_with_usage": len(costs),
    }


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--region", default=os.environ.get("AWS_REGION", "eu-north-1"))
    parser.add_argument("--model", choices=MODELS, default=MODELS[0])
    parser.add_argument("--repeats", type=int, choices=(1, 2, 3), default=2)
    parser.add_argument("--effort", choices=("low", "medium", "high", "xhigh", "max"), default="medium")
    parser.add_argument("--case", action="append", choices=[case["id"] for case in CASES])
    parser.add_argument("--output", required=True, help="Filename for the resulting JSON (must not exist).")
    args = parser.parse_args()
    if not re.fullmatch(r"[a-z]{2}(?:-[a-z]+)+-[0-9]+", args.region):
        parser.error("Expected an AWS region, such as eu-north-1")
    token = os.environ.get("AWS_BEARER_TOKEN_BEDROCK", "").strip()
    if not token:
        parser.error("Set AWS_BEARER_TOKEN_BEDROCK in this process environment")

    cases = [case for case in CASES if args.case is None or case["id"] in args.case]
    metadata = {
        "started_utc": datetime.now(timezone.utc).isoformat(),
        "region": args.region,
        "model": args.model,
        "reasoning_effort": args.effort,
        "max_completion_tokens": MAX_COMPLETION_TOKENS,
        "repeats": args.repeats,
        "planned_requests": len(cases) * args.repeats,
        "case_ids": [case["id"] for case in cases],
        "qaf_source_urls": {case["id"]: case["source_urls"] for case in cases if "source_urls" in case},
    }
    results = []
    try:
        output = open(args.output, "x", encoding="utf-8")
    except OSError as exc:
        parser.error(str(exc))
    with output:
        try:
            for repeat in range(1, args.repeats + 1):
                for case in cases:
                    result = benchmark_case(case, args.region, args.model, args.effort, token)
                    results.append({"case": case["id"], "repeat": repeat, **result})
                    status = result.get("error", "pass" if result.get("passed") else "fail")
                    code = f" HTTP {result['http_status']}" if "http_status" in result else ""
                    print(f"{case['id']} #{repeat} {status}{code} ({result['total_s']:.2f}s)", flush=True)
                    if result.get("http_status") in (400, 401, 403, 404):
                        return 1
        finally:
            summary = summarize(results)
            json.dump({**metadata, "summary": summary, "results": results}, output, indent=2, ensure_ascii=False)
            output.write("\n")
            print(json.dumps(summary), flush=True)
    return int(any("error" in result for result in results))


if __name__ == "__main__":
    raise SystemExit(main())
