"""ClawPrompt CLI - starts the teleprompter server."""
import http.server
import json
import os
import socket
import subprocess
import sys
import threading
from pathlib import Path

WEB_DIR = Path(__file__).parent / "web"
PORT = int(os.environ.get("PORT", "7870"))


def get_lan_ip():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("8.8.8.8", 80))
        ip = s.getsockname()[0]
        s.close()
        return ip
    except Exception:
        return "127.0.0.1"


def main():
    # Check if node is available
    node = "node"
    try:
        subprocess.run([node, "--version"], capture_output=True, check=True)
    except (FileNotFoundError, subprocess.CalledProcessError):
        print("Error: Node.js is required. Install it from https://nodejs.org/")
        sys.exit(1)

    server_js = WEB_DIR / "server.js"
    if not server_js.exists():
        print(f"Error: server.js not found at {server_js}")
        sys.exit(1)

    # Install deps if needed
    node_modules = WEB_DIR / "node_modules"
    if not node_modules.exists():
        print("Installing dependencies...")
        subprocess.run(["npm", "install", "--silent"], cwd=str(WEB_DIR), check=True)

    print(f"\n🎬 ClawPrompt")
    print(f"   Computer: http://localhost:{PORT}")
    print(f"   Phone:    http://{get_lan_ip()}:{PORT}/remote\n")

    os.execvp(node, [node, str(server_js)])


if __name__ == "__main__":
    main()
