import json
import os

from minio import Minio

mc = Minio(os.environ["MINIO_ENDPOINT"], access_key=os.environ["MINIO_ACCESS_KEY"], secret_key=os.environ["MINIO_SECRET_KEY"], secure=False)

# Find the failed doc's LLM result
target = "b6003360"
objs = [o for o in mc.list_objects("stonks-llm-results", recursive=True) if target in o.object_name]
if not objs:
    # Search all recent results
    all_objs = sorted(mc.list_objects("stonks-llm-results", recursive=True), key=lambda o: o.last_modified, reverse=True)
    for o in all_objs[:5]:
        if target in o.object_name:
            objs.append(o)

for o in objs:
    data = json.loads(mc.get_object("stonks-llm-results", o.object_name).read())
    print(f"success: {data.get('success')}")
    print(f"total_duration_ms: {data.get('total_duration_ms')}")
    for i, att in enumerate(data.get("attempts", [])):
        print(f"\n  attempt {i+1}:")
        print(f"    error: {att.get('error')}")
        print(f"    duration_ms: {att.get('duration_ms')}")
        print(f"    retryable: {att.get('retryable')}")
        raw = att.get("raw_output", "")
        if raw:
            print(f"    output ({len(raw)} chars): {raw[:200]}")
        else:
            print("    output: (empty)")

if not objs:
    print(f"No LLM result found for {target}")
    print("Checking most recent failed result instead...")
    all_objs = sorted(mc.list_objects("stonks-llm-results", recursive=True), key=lambda o: o.last_modified, reverse=True)
    for o in all_objs[:10]:
        data = json.loads(mc.get_object("stonks-llm-results", o.object_name).read())
        if not data.get("success"):
            print(f"\nFailed: {o.object_name}")
            for i, att in enumerate(data.get("attempts", [])):
                print(f"  attempt {i+1}: error={att.get('error')} duration={att.get('duration_ms')}ms")
            break
