#!/usr/bin/env python3
"""
send.py — ChatGPT daemon client
---------------------------------
Sends a prompt to the running daemon and prints the response.
Falls back gracefully if the daemon isn't running.

Usage:
    python3 /home/node/.claude/skills/chatgpt/scripts/send.py "your prompt here"

    # Or with a custom port:
    python3 send.py --port 9224 "your prompt"
"""

import argparse
import json
import sys
import urllib.error
import urllib.request
from pathlib import Path

DEFAULT_PORT   = 9223
DAEMON_SCRIPT  = Path(__file__).parent / "daemon.py"


def api(port: int, path: str, body: dict = None) -> dict | None:
    url  = f"http://localhost:{port}{path}"
    data = json.dumps(body).encode() if body else None
    req  = urllib.request.Request(
        url, data=data,
        headers={"Content-Type": "application/json"} if data else {},
        method="POST" if data else "GET",
    )
    try:
        with urllib.request.urlopen(req, timeout=300) as resp:
            return json.loads(resp.read())
    except urllib.error.URLError:
        return None


def daemon_running(port: int = DEFAULT_PORT) -> bool:
    return api(port, "/health") is not None


def main():
    parser = argparse.ArgumentParser(description="Send a prompt to the ChatGPT daemon")
    parser.add_argument("prompt", help="Prompt to send")
    parser.add_argument("--port", type=int, default=DEFAULT_PORT)
    args = parser.parse_args()

    # Health check
    health = api(args.port, "/health")
    if health is None:
        print(f"[send] Daemon not running on port {args.port}. Start it with:")
        print(f"  PYTHONUNBUFFERED=1 python3 {DAEMON_SCRIPT} &")
        sys.exit(1)
    print(f"[send] Daemon OK — {health.get('url', '?')}")

    print(f"[send] Sending: {args.prompt}")
    result = api(args.port, "/send", {"prompt": args.prompt})
    if result is None:
        print("[send] No response from daemon (timeout or crash)")
        sys.exit(1)

    if "error" in result:
        print(f"[send] Error: {result['error']}")
        sys.exit(1)

    kind = result.get("kind")
    if kind == "text":
        print(f"\n--- Response ---\n{result.get('text', '')}")
    elif kind == "image":
        images = result.get("images", [])
        if images:
            print(f"\n--- Images saved ---")
            for p in images:
                print(f"  {p}")
        else:
            print("[send] Image generation completed but no files downloaded")
    elif kind == "timeout":
        print("[send] Timed out waiting for ChatGPT response")
        sys.exit(1)
    else:
        print(f"[send] Unknown response: {result}")

    conv_url = result.get("conv_url")
    if conv_url:
        print(f"\n--- Conversation ---\n  {conv_url}")


if __name__ == "__main__":
    main()
