#!/usr/bin/env python3
"""
Headless Moondream Station launcher for open-agents.

Starts the Moondream vision model REST API server on port 2020 without
the interactive REPL. Designed to be auto-launched by the VisionTool.

Usage:
  python start-moondream.py [--port 2020] [--host 127.0.0.1]

Environment:
  HF_TOKEN  - HuggingFace token (optional, for gated models)
"""

import sys
import signal
import time
import argparse

def main():
    parser = argparse.ArgumentParser(description="Start Moondream Station REST server")
    parser.add_argument("--port", type=int, default=2020, help="Server port (default: 2020)")
    parser.add_argument("--host", default="127.0.0.1", help="Server host (default: 127.0.0.1)")
    parser.add_argument("--model", default=None, help="Model to use (default: auto-detect, prefers non-gated moondream-2)")
    args = parser.parse_args()

    try:
        from moondream_station.core.config import ConfigManager
        from moondream_station.core.manifest import ManifestManager
        from moondream_station.core.models import ModelManager
        from moondream_station.core.service import ServiceManager
        from moondream_station.core.analytics import Analytics
        from moondream_station.session import SessionState
        from moondream_station.ui.display import Display
    except ImportError:
        print("ERROR: moondream-station not installed. Install with: pip install moondream-station", file=sys.stderr)
        sys.exit(1)

    print(f"[moondream] Initializing...", flush=True)

    config = ConfigManager()
    config.set("service_host", args.host)
    config.set("service_port", args.port)

    manifest_manager = ManifestManager(config)
    analytics = Analytics(config, manifest_manager)
    display = Display()
    models = ModelManager(config, manifest_manager)
    session_state = SessionState()

    # Load manifest
    manifest_url = "https://m87-md-prod-assets.s3.us-west-2.amazonaws.com/station/mds2/production_manifest.json"
    print(f"[moondream] Loading manifest...", flush=True)
    try:
        manifest_manager.load_manifest(manifest_url, analytics, display)
    except Exception as e:
        print(f"ERROR: Failed to load manifest: {e}", file=sys.stderr)
        sys.exit(1)

    # Select model — prefer moondream-2 (non-gated) unless overridden
    import os
    model_name = args.model
    if not model_name:
        # Prefer moondream-2 (no HF token required) unless user has HF_TOKEN
        has_hf_token = bool(os.environ.get("HF_TOKEN") or config.get("hf_token"))
        if has_hf_token:
            model_name = manifest_manager.get_available_default_model()
        else:
            model_name = "moondream-2"
    if not model_name:
        model_name = manifest_manager.get_available_default_model()
    if not model_name:
        print("ERROR: No model available", file=sys.stderr)
        sys.exit(1)

    print(f"[moondream] Switching to model: {model_name}", flush=True)
    if not models.switch_model(model_name, display):
        print(f"ERROR: Failed to switch to model {model_name}", file=sys.stderr)
        sys.exit(1)

    # Start REST server
    service = ServiceManager(config, manifest_manager, session_state, analytics)
    print(f"[moondream] Starting REST server on {args.host}:{args.port}...", flush=True)

    if not service.start(model_name, args.port):
        print("ERROR: Failed to start REST server", file=sys.stderr)
        sys.exit(1)

    print(f"[moondream] Server running at http://{args.host}:{args.port}/v1", flush=True)
    print(f"[moondream] Endpoints: /v1/caption, /v1/query, /v1/detect, /v1/point", flush=True)
    print(f"READY", flush=True)

    # Handle shutdown
    def shutdown(signum, frame):
        print(f"\n[moondream] Shutting down...", flush=True)
        service.stop()
        sys.exit(0)

    signal.signal(signal.SIGTERM, shutdown)
    signal.signal(signal.SIGINT, shutdown)

    # Keep alive
    try:
        while service.is_running():
            time.sleep(1)
    except KeyboardInterrupt:
        shutdown(None, None)

    print("[moondream] Server stopped", flush=True)

if __name__ == "__main__":
    main()
