#!/usr/bin/env python3
"""
TaskingTech Desktop Agent — cross-platform native computer control.

Usage:
  tt-desktop setup          Set your API key (one-time)
  tt-desktop run             Start the agent (foreground)
  tt-desktop app             Launch GUI desktop app (pywebview)
  tt-desktop tray            Start with system tray icon
  tt-desktop status          Check connection status
  tt-desktop --help          Show help
"""

import sys
import os
import argparse

from .config import load_config, set_api_key, save_config, CONFIG_FILE


LOGO_ASCII = r"""
  ______           __   _            ______          __
 /_  __/___ ______/ /__(_)___  ____ /_  __/__  _____/ /_
  / / / __ `/ ___/ //_/ / __ \/ __ `// / / _ \/ ___/ __ \
 / / / /_/ (__  ) ,< / / / / / /_/ // / /  __/ /__/ / / /
/_/  \__,_/____/_/|_/_/_/ /_/\__, //_/  \___/\___/_/ /_/
                            /____/
           Desktop Agent v0.2.0
"""


def cmd_setup(args):
    """Interactive setup — set API key."""
    print(LOGO_ASCII)
    print("Setup: Configure your TaskingTech Desktop Agent\n")
    print("To get an API key:")
    print("  1. Go to https://tasking.tech")
    print("  2. Open TaskingBot chat")
    print("  3. Type: /desktop-agent-key")
    print("  4. Copy the key shown\n")

    config = load_config()

    key = input("Paste your API key: ").strip()
    if not key:
        print("No key provided. Aborting.")
        return

    config["api_key"] = key

    server = input(f"Server URL [{config['server_url']}]: ").strip()
    if server:
        config["server_url"] = server

    save_config(config)
    print(f"\nConfig saved to {CONFIG_FILE}")
    print("Run 'tt-desktop run' to start the agent.")


def cmd_run(args):
    """Start the agent in foreground mode."""
    config = load_config()
    if not config.get("api_key"):
        print("No API key configured. Run 'tt-desktop setup' first.")
        sys.exit(1)

    print(LOGO_ASCII)
    print(f"Server:   {config['server_url']}")
    print(f"Agent ID: {config['agent_id'][:12]}...")
    print(f"Config:   {CONFIG_FILE}")
    print()

    from .poller import DesktopAgentPoller
    poller = DesktopAgentPoller(config)
    poller.run()


def cmd_tray(args):
    """Start with system tray icon."""
    config = load_config()
    if not config.get("api_key"):
        print("No API key configured. Run 'tt-desktop setup' first.")
        sys.exit(1)

    try:
        import pystray
        from PIL import Image, ImageDraw
    except ImportError:
        print("System tray requires pystray and Pillow: pip install pystray Pillow")
        print("Falling back to foreground mode...")
        cmd_run(args)
        return

    from .poller import DesktopAgentPoller

    # Create tray icon — Tasking.tech logo (orange T on dark background)
    def create_icon():
        img = Image.new("RGBA", (64, 64), (0, 0, 0, 0))
        draw = ImageDraw.Draw(img)
        # Dark rounded background
        draw.rounded_rectangle([2, 2, 62, 62], radius=12, fill=(26, 26, 46, 255))
        # Orange "T" letter
        draw.rectangle([14, 14, 50, 22], fill=(201, 130, 42, 255))  # top bar
        draw.rectangle([28, 22, 36, 50], fill=(201, 130, 42, 255))  # vertical bar
        return img

    poller = DesktopAgentPoller(config)
    status_text = "Connecting..."

    def on_status(msg):
        nonlocal status_text
        status_text = msg

    poller.on_status = on_status

    def quit_agent(icon, item):
        poller.running = False
        icon.stop()

    def get_status(item):
        return status_text

    menu = pystray.Menu(
        pystray.MenuItem("TaskingTech Desktop Agent", None, enabled=False),
        pystray.Menu.SEPARATOR,
        pystray.MenuItem(lambda item: status_text, None, enabled=False),
        pystray.Menu.SEPARATOR,
        pystray.MenuItem("Quit", quit_agent),
    )

    icon = pystray.Icon(
        "tt-desktop",
        create_icon(),
        "TaskingTech Desktop Agent",
        menu,
    )

    # Start poller in background
    poller.run_in_background()

    # Run tray icon (blocks)
    icon.run()


def cmd_app(args):
    """Launch the GUI desktop application."""
    config = load_config()
    print(LOGO_ASCII)
    print("Launching TaskingBot AI desktop app...")
    print()

    from .app import launch_app
    launch_app(config)


def cmd_status(args):
    """Check connection status."""
    config = load_config()
    if not config.get("api_key"):
        print("Not configured. Run 'tt-desktop setup' first.")
        return

    from .poller import DesktopAgentPoller
    poller = DesktopAgentPoller(config)
    ok = poller.send_heartbeat()
    if ok:
        print(f"Connected to {config['server_url']}")
    else:
        print("Connection failed — check API key and server URL")


def main():
    parser = argparse.ArgumentParser(
        description="TaskingTech Desktop Agent — native computer control",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=LOGO_ASCII,
    )
    subparsers = parser.add_subparsers(dest="command")

    subparsers.add_parser("setup", help="Configure API key (one-time)")
    subparsers.add_parser("run", help="Start agent in foreground")
    subparsers.add_parser("app", help="Launch GUI desktop app (pywebview)")
    subparsers.add_parser("tray", help="Start with system tray icon")
    subparsers.add_parser("status", help="Check connection status")

    args = parser.parse_args()

    commands = {
        "setup": cmd_setup,
        "run": cmd_run,
        "app": cmd_app,
        "tray": cmd_tray,
        "status": cmd_status,
    }

    if args.command in commands:
        commands[args.command](args)
    else:
        parser.print_help()


if __name__ == "__main__":
    main()
