#!/usr/bin/env python3
"""
CLI client for the Cube Agent API.

Usage:
    python cli.py "Connect me to staging-int"
    python cli.py --interactive
    python cli.py --session abc123 "What's the status?"
"""

import argparse
import sys
import json
import httpx
from typing import Optional

DEFAULT_URL = "http://localhost:8000"


def chat_streaming(base_url: str, message: str, session_id: Optional[str] = None):
    """Send a message and stream the response."""
    url = f"{base_url}/chat"
    payload = {"message": message}
    if session_id:
        payload["session_id"] = session_id

    current_session_id = None

    with httpx.stream("POST", url, json=payload, timeout=300.0) as response:
        # Get session ID from headers
        current_session_id = response.headers.get("x-session-id")

        for line in response.iter_lines():
            if line.startswith("data: "):
                data = json.loads(line[6:])
                event_type = data.get("event")
                event_data = data.get("data", {})

                if event_type == "thinking":
                    content = event_data.get("content") or event_data.get("message", "")
                    if content:
                        print(f"\033[90m[thinking] {content}\033[0m")

                elif event_type == "tool_call":
                    name = event_data.get("name")
                    input_data = json.dumps(event_data.get("input", {}))[:100]
                    print(f"\033[93m[tool] {name}({input_data})\033[0m")

                elif event_type == "tool_result":
                    name = event_data.get("name")
                    content = event_data.get("content", "")[:200]
                    print(f"\033[92m[result] {name}: {content}...\033[0m")

                elif event_type == "text":
                    content = event_data.get("content", "")
                    print(f"\n{content}")

                elif event_type == "done":
                    current_session_id = event_data.get("session_id")
                    turns = event_data.get("turns", 0)
                    print(f"\n\033[90m[done in {turns} turns, session: {current_session_id}]\033[0m")

                elif event_type == "error":
                    message = event_data.get("message", "Unknown error")
                    print(f"\033[91m[error] {message}\033[0m")
                    sys.exit(1)

    return current_session_id


def chat_sync(base_url: str, message: str, session_id: Optional[str] = None):
    """Send a message and wait for complete response."""
    url = f"{base_url}/chat/sync"
    payload = {"message": message}
    if session_id:
        payload["session_id"] = session_id

    response = httpx.post(url, json=payload, timeout=300.0)

    if response.status_code != 200:
        print(f"Error: {response.text}")
        sys.exit(1)

    data = response.json()
    print(data.get("response", ""))
    return data.get("session_id")


def health_check(base_url: str):
    """Check agent health."""
    response = httpx.get(f"{base_url}/health", timeout=10.0)
    data = response.json()

    print("Cube Agent Status")
    print("=" * 40)
    print(f"Status: {data.get('status')}")
    print(f"Model: {data.get('model')}")
    print(f"Apollo Configured: {data.get('apollo_configured')}")
    print("\nTools:")
    for tool, available in data.get("tools", {}).items():
        status = "OK" if available else "MISSING"
        icon = "[+]" if available else "[ ]"
        print(f"  {icon} {tool}: {status}")


def interactive_mode(base_url: str, session_id: Optional[str] = None):
    """Run in interactive mode."""
    print("Cube Agent - Interactive Mode")
    print("Type 'exit' or Ctrl+C to quit")
    print("=" * 40)

    current_session = session_id

    while True:
        try:
            prompt = input("\n> ").strip()
            if not prompt:
                continue
            if prompt.lower() in ["exit", "quit", "q"]:
                break

            current_session = chat_streaming(base_url, prompt, current_session)

        except KeyboardInterrupt:
            print("\nGoodbye!")
            break
        except Exception as e:
            print(f"Error: {e}")


def main():
    parser = argparse.ArgumentParser(description="Cube Agent CLI")
    parser.add_argument("message", nargs="?", help="Message to send")
    parser.add_argument("--url", default=DEFAULT_URL, help="Agent API URL")
    parser.add_argument("--session", "-s", help="Session ID for conversation continuity")
    parser.add_argument("--interactive", "-i", action="store_true", help="Interactive mode")
    parser.add_argument("--health", action="store_true", help="Check agent health")
    parser.add_argument("--sync", action="store_true", help="Use synchronous API (no streaming)")

    args = parser.parse_args()

    if args.health:
        health_check(args.url)
        return

    if args.interactive:
        interactive_mode(args.url, args.session)
        return

    if not args.message:
        parser.print_help()
        return

    if args.sync:
        chat_sync(args.url, args.message, args.session)
    else:
        chat_streaming(args.url, args.message, args.session)


if __name__ == "__main__":
    main()
