#!/usr/bin/env python3
"""
Live integration smoke test for tracing + tool decorators.

Usage:
    python tests/test_tracing_tool_live.py
"""
import os
import sys
import time

sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))

try:
    from dotenv import load_dotenv

    load_dotenv(os.path.join(os.path.dirname(__file__), "..", ".env"))
except ImportError:
    pass

from cascade import init_tracing, trace_run, trace_agent, tool, function, set_session_id


@function
def normalize_text(text: str) -> str:
    return " ".join(text.strip().split())


@tool
def summarize(text: str) -> str:
    cleaned = normalize_text(text)
    return f"Summary[{len(cleaned)}]: {cleaned[:40]}"


@tool
def risky_divide(a: float, b: float) -> float:
    return a / b


def main() -> None:
    endpoint = os.getenv("CASCADE_ENDPOINT", "http://localhost:8000/v1/traces")
    api_key = os.getenv("CASCADE_API_KEY")
    project = "tracing_tool_live_test"

    print("=" * 64)
    print("Tracing + Tool Live Integration Test")
    print("=" * 64)
    print(f"Endpoint: {endpoint}")
    print(f"Project : {project}")
    if not api_key:
        print("Warning: CASCADE_API_KEY not set. Running with unauthenticated local setup.")

    init_tracing(project=project, endpoint=endpoint, api_key=api_key)
    set_session_id("live-session-001")

    caught_expected_error = False
    with trace_run("TracingToolLiveRun", metadata={"source": "test_tracing_tool_live.py"}) as root:
        trace_id = format(root.get_span_context().trace_id, "032x")
        print(f"[1] Root trace started: {trace_id}")

        with trace_agent("LiveToolAgent", metadata={"phase": "smoke"}):
            output = summarize("   tracing    and     tools    integration   ")
            print(f"[2] summarize() output: {output}")
            assert output.startswith("Summary["), "summarize() returned unexpected output"

            try:
                risky_divide(10, 0)
            except ZeroDivisionError:
                caught_expected_error = True
                print("[3] risky_divide() failure path captured (expected ZeroDivisionError)")

    assert caught_expected_error, "Expected risky_divide(10, 0) to raise ZeroDivisionError"

    print("[4] Waiting 2s for span export...")
    time.sleep(2)
    print("[5] Live tracing/tool test completed successfully.")
    print("Open dashboard at: http://localhost:3000")


if __name__ == "__main__":
    main()
