"""
Example: using the LiteFold SDK from an OpenClaw agent.

Demonstrates the full lifecycle:
  1. List existing chats
  2. Fire-and-forget a new chat message
  3. Wait for completion via chat_status
  4. Read blocks (assistant text, tool results, bash outputs)
  5. Browse workspace files

Run:
    pip install -e ../
    LITEFOLD_API_KEY=lf_... python basic_agent.py
"""

import os
import time
from litefold import Client, LiteFoldError

API_KEY = os.environ["LITEFOLD_API_KEY"]
BASE_URL = os.environ.get("LITEFOLD_BASE_URL", "https://agentsapi.litefold.ai")
PROJECT = "Default"
CHAT_NAME = "openclaw-agent-run-1"


def main():
    client = Client(api_key=API_KEY, base_url=BASE_URL)

    # ── 1. List recent chats ────────────────────────────────────
    chats = client.rosalind.list_chats(project=PROJECT, limit=5)
    print(f"Recent chats ({len(chats)}):")
    for c in chats:
        print(f"  {c.chat_name:40s}  tokens={c.total_input_tokens + c.total_output_tokens:>8}  device={c.device}")

    # ── 2. Create chat + send message (fire-and-forget) ─────────
    client.rosalind.create_chat(
        project=PROJECT,
        chat_name=CHAT_NAME,
        description="OpenClaw agent run",
    )
    client.rosalind.send_message(
        project=PROJECT,
        chat_name=CHAT_NAME,
        message="Briefly describe the role of KRAS G12D mutation in cancer.",
        mode="pro",
        depth="balanced",
    )
    print(f"\nMessage sent to {CHAT_NAME} — agent is running.")

    # ── 3. Wait until done via chat_status ──────────────────────
    while True:
        status = client.rosalind.chat_status(project=PROJECT, chat_name=CHAT_NAME)
        if not status.is_running:
            print(f"Agent finished (status={status.status})")
            break
        print(f"  still running (task={status.task_id})")
        time.sleep(5)

    # ── 4. Read blocks ──────────────────────────────────────────
    total = client.rosalind.list_blocks(project=PROJECT, chat_name=CHAT_NAME)
    print(f"\nTotal blocks: {total}")

    blocks = client.rosalind.get_blocks(project=PROJECT, chat_name=CHAT_NAME)
    for b in blocks:
        if b.assistant_message:
            print(f"\n=== Assistant (block {b.index}) ===")
            print(b.assistant_message[:500])
        elif b.content_type == "tool_use":
            print(f"  [tool_use] {b.tool_name}")
        elif b.content_type == "mcp_result" and b.is_output_panel:
            print(f"  [output]   {b.tool_name} → {str(b.tool_result)[:120]}")

    # ── 5. Bash outputs ─────────────────────────────────────────
    bash = client.rosalind.get_bash_outputs(project=PROJECT, chat_name=CHAT_NAME)
    if bash:
        print(f"\n=== Bash Outputs ({len(bash)}) ===")
        for b in bash:
            print(f"  $ {b.command}")
            print(f"    exit={b.exit_code}  output={str(b.output)[:120]}")

    # ── 6. Workspace files ──────────────────────────────────────
    ws = client.rosalind.workspace(project=PROJECT, chat_name=CHAT_NAME)
    folders = ws.list_folders()
    print(f"\nWorkspace folders: {folders}")

    for folder in folders[:3]:
        files = ws.list_files(folder=folder)
        if files:
            print(f"  {folder}/ ({len(files)} files)")
            first = files[0]
            fc = ws.get_file_content(first.location)
            print(f"    {first.name}: {fc.content[:200]}...")

    client.close()


if __name__ == "__main__":
    try:
        main()
    except LiteFoldError as e:
        print(f"LiteFold SDK error: {e}")
