"""Dev target walkthrough — local JSONL recording with OpenAI SDK."""

import openai

import caliper
from caliper._export import DevHandler

######################################################################
# Basic non-streaming call
######################################################################


def basic_call(client: openai.OpenAI) -> None:
    response = client.chat.completions.create(
        model="gpt-4o",
        max_tokens=128,
        messages=[{"role": "user", "content": "Say hello in exactly 5 words."}],
    )
    print(response.choices[0].message.content)


######################################################################
# Streaming call
######################################################################


def streaming_call(client: openai.OpenAI) -> None:
    with client.chat.completions.create(
        model="gpt-4o",
        max_tokens=128,
        messages=[{"role": "user", "content": "Tell me a one-sentence joke."}],
        stream=True,
        stream_options={"include_usage": True},
    ) as stream:
        for chunk in stream:
            content = None
            if chunk.choices:
                content = chunk.choices[0].delta.content
            if content:
                print(content, end="", flush=True)
        print()


######################################################################
# Feature metadata — context-scoped and per-request
######################################################################


def feature_metadata(client: openai.OpenAI) -> None:
    with caliper.features(feature="onboarding", user_id="demo-123"):
        response = client.chat.completions.create(
            model="gpt-4o",
            max_tokens=64,
            messages=[{"role": "user", "content": "What is 2 + 2?"}],
        )
        print(response.choices[0].message.content)

    # caliper_metadata is a per-request override — merged with context metadata
    response = client.chat.completions.create(
        model="gpt-4o",
        max_tokens=64,
        messages=[{"role": "user", "content": "What is 3 + 3?"}],
        caliper_metadata={"campaign": "q4", "experiment": "v2"},
    )
    print(response.choices[0].message.content)


######################################################################
# Multi-turn linking
######################################################################


def multi_turn_linking(client: openai.OpenAI) -> None:
    # First turn
    client.chat.completions.create(
        model="gpt-4o",
        max_tokens=64,
        messages=[{"role": "user", "content": "What is the capital of France?"}],
    )
    first_id = caliper.last_request_id()
    print(f"First request ID: {first_id}")

    # Second turn — linked to the first via previous_request
    with caliper.features(previous_request=first_id, feature="followup"):
        followup = client.chat.completions.create(
            model="gpt-4o",
            max_tokens=64,
            messages=[{"role": "user", "content": "And what is its population?"}],
        )
        print(followup.choices[0].message.content)


######################################################################
# Post-request annotations
######################################################################


def annotations(client: openai.OpenAI) -> None:
    client.chat.completions.create(
        model="gpt-4o",
        max_tokens=64,
        messages=[{"role": "user", "content": "Recommend a book about Python."}],
    )

    request_id = caliper.last_request_id()
    print(f"Annotating request: {request_id}")

    caliper.annotate(sentiment="positive")
    caliper.annotate(request_id, user_feedback="thumbs_up")
    caliper.annotate(request_id, reviewed_by="human")


######################################################################
# Inspect captured records (dev target only)
######################################################################


def inspect_records() -> None:
    handler = DevHandler()
    print("\n--- Captured records ---")
    for record in handler.get_records():
        print(
            f"  model={record['model']}"
            f"  in={record['tokens_input']}"
            f"  out={record['tokens_output']}"
            f"  status={record['status']}"
            f"  request_id={record['request_id']}"
        )

    print("\n--- Captured annotations ---")
    for annotation in handler.get_annotations():
        print(f"  request_id={annotation['request_id']}  metadata={annotation['metadata']}")


######################################################################
# Main
######################################################################


def main() -> None:
    caliper.init(target="dev")
    client = openai.OpenAI()

    print("=== Basic call ===")
    basic_call(client)

    print("\n=== Streaming call ===")
    streaming_call(client)

    print("\n=== Feature metadata ===")
    feature_metadata(client)

    print("\n=== Multi-turn linking ===")
    multi_turn_linking(client)

    print("\n=== Annotations ===")
    annotations(client)

    caliper.shutdown()
    inspect_records()


if __name__ == "__main__":
    main()
