import argparse
import sys

from gtv.app import GtvApp
from gtv.constants import BANNER, REMOTE_KEY_COMMANDS


def main():
    app = GtvApp()

    if len(sys.argv) > 1:
        subcmd = sys.argv[1]

        if subcmd == "discover":
            app.onecmd_plus_hooks("discover " + " ".join(sys.argv[2:]))
        elif subcmd == "pair":
            app.onecmd_plus_hooks("pair " + " ".join(sys.argv[2:]))
        elif subcmd == "connect":
            host_args = " ".join(sys.argv[2:])
            app.onecmd_plus_hooks("connect " + host_args)
            if app.remote:
                app.cmdloop()
        elif subcmd == "send":
            p = argparse.ArgumentParser()
            p.add_argument("--host", required=True)
            p.add_argument("command")
            p.add_argument("value", nargs="?", default="")
            parsed, _ = p.parse_known_args(sys.argv[2:])

            app.onecmd_plus_hooks(f"connect {parsed.host}")
            if app.remote:
                cmd_name = parsed.command.lower()
                if cmd_name in ("app", "open", "key"):
                    app.onecmd_plus_hooks(f"{cmd_name} {parsed.value}")
                elif cmd_name in REMOTE_KEY_COMMANDS:
                    app.onecmd_plus_hooks(cmd_name)
                else:
                    app.perror(f"Unknown command: {cmd_name}")
                app.onecmd_plus_hooks("disconnect")
        elif subcmd == "status":
            host = sys.argv[2] if len(sys.argv) > 2 else None
            if host and host == "--host" and len(sys.argv) > 3:
                host = sys.argv[3]
            if host:
                app.onecmd_plus_hooks(f"connect {host}")
                if app.remote:
                    app.onecmd_plus_hooks("status")
                    app.onecmd_plus_hooks("disconnect")
            else:
                app.perror("Usage: gtv-remote status --host <ip>")
        elif subcmd in ("--help", "-h"):
            print(BANNER)
            print("Usage: gtv-remote [command]\n")
            print("Commands:")
            print("  (none)              Interactive mode (discover + connect)")
            print("  discover            Scan for devices on the network")
            print("  pair [host]         Pair with a device")
            print("  connect [host]      Connect and start interactive remote")
            print("  send --host IP cmd  Send a one-shot command")
            print("  status --host IP    Show device status")
            print("  --help              Show this help\n")
        else:
            app.cmdloop()
    else:
        app.cmdloop()
