#!/usr/bin/env python3
"""
SAL-v4 Launcher
Quick launcher that handles API key configuration.
"""

import os
import sys

CONFIG_FILE = os.path.join(os.path.dirname(__file__), ".env")


def load_api_key():
    """Load API key from env or config file."""
    key = os.environ.get("ZAI_API_KEY")
    if key:
        return key

    if os.path.exists(CONFIG_FILE):
        with open(CONFIG_FILE, "r") as f:
            for line in f:
                line = line.strip()
                if line.startswith("ZAI_API_KEY="):
                    return line.split("=", 1)[1]

    return None


def save_api_key(key: str):
    """Save API key to config file."""
    with open(CONFIG_FILE, "w") as f:
        f.write(f"ZAI_API_KEY={key}\n")
    print(f"[OK] API key saved to {CONFIG_FILE}")


def main():
    api_key = load_api_key()

    if not api_key:
        print("=" * 50)
        print("  SAL-v4 Harness - First Time Setup")
        print("=" * 50)
        print()
        print("No Z.AI API key found.")
        print("Get your key from: https://z.ai")
        print()

        try:
            api_key = input("Enter your Z.AI API key: ").strip()
            if api_key:
                save_api_key(api_key)
            else:
                print("[ERROR] No key provided")
                sys.exit(1)
        except KeyboardInterrupt:
            print("\n[Cancelled]")
            sys.exit(1)

    os.environ["ZAI_API_KEY"] = api_key

    print()
    print("SAL-v4 Harness Launcher")
    print("=" * 50)
    print("  1. TUI (Simple)    - Step-by-step interface")
    print("  2. TUI (Live)      - Split-screen live updates")
    print("  3. Chat            - Simple chat interface")
    print("  4. Health Check    - Verify API connection")
    print("  5. Harness Demo    - Run demo loop")
    print()

    try:
        choice = input("Select (1-5): ").strip()
    except KeyboardInterrupt:
        print("\n[Cancelled]")
        sys.exit(0)

    if choice == "1":
        from tui import main as tui_main

        tui_main()
    elif choice == "2":
        from tui_live import main as tui_live_main

        tui_live_main()
    elif choice == "3":
        from chat import main as chat_main

        chat_main()
    elif choice == "4":
        from health import main as health_main

        health_main()
    elif choice == "5":
        from harness import main as harness_main

        harness_main()
    else:
        print(f"Unknown choice: {choice}")


if __name__ == "__main__":
    main()
