"""
MineConnect Client CLI - Interactive command-line interface

Usage:
    python -m mineconnect.client.cli
    OR
    mineconnect-client (after installation)
"""

import sys
import argparse
import time
from .cli_client import MineConnectClient


class InteractiveCLI:
    """Interactive CLI for MineConnect client."""
    
    def __init__(self, domain: str = "ideadev.me"):
        self.client = MineConnectClient(
            domain=domain,
            on_log=self._log,
            on_status=self._status
        )
        self.running = True
    
    def _log(self, msg: str):
        """Log message handler."""
        print(f"  {msg}")
    
    def _status(self, tunnel: str, status: str):
        """Status update handler."""
        status_symbols = {
            "disconnected": "⭘",
            "connecting": "⋯",
            "connected": "●",
            "reconnecting": "◐",
            "error": "✕",
        }
        symbol = status_symbols.get(status, "?")
        print(f"  {symbol} {tunnel.capitalize()}: {status}")
    
    def show_banner(self):
        """Display welcome banner."""
        print("\n" + "="*60)
        print("  MineConnect Client - Interactive CLI")
        print("  Domain: " + self.client.domain)
        print("="*60 + "\n")
    
    def show_help(self):
        """Display available commands."""
        print("\nAvailable commands:")
        print("  connect [java|bedrock|both]  - Connect tunnel(s)")
        print("  disconnect [java|bedrock]    - Disconnect tunnel(s)")
        print("  status                       - Show connection status")
        print("  help                         - Show this help")
        print("  quit / exit                  - Exit client\n")
    
    def show_status(self):
        """Display current status."""
        status = self.client.get_status()
        print("\nStatus:")
        print(f"  Java:    {status['java']}")
        print(f"  Bedrock: {status['bedrock']}\n")
    
    def handle_connect(self, args: list):
        """Handle connect command."""
        what = args[0] if args else "both"
        
        if what in ("java", "both"):
            self.client.connect_java()
        if what in ("bedrock", "both"):
            self.client.connect_bedrock()
        
        if what not in ("java", "bedrock", "both"):
            print(f"  Unknown target: {what}. Use java, bedrock, or both")
    
    def handle_disconnect(self, args: list):
        """Handle disconnect command."""
        what = args[0] if args else "all"
        
        if what in ("java", "all"):
            self.client.disconnect_java()
        if what in ("bedrock", "all"):
            self.client.disconnect_bedrock()
        
        if what not in ("java", "bedrock", "all"):
            print(f"  Unknown target: {what}. Use java, bedrock, or leave empty for all")
    
    def process_command(self, line: str):
        """Process a single command."""
        parts = line.strip().split()
        if not parts:
            return
        
        cmd = parts[0].lower()
        args = parts[1:]
        
        if cmd in ("quit", "exit", "q"):
            print("\nDisconnecting and exiting...")
            self.client.disconnect()
            self.running = False
        elif cmd == "connect":
            self.handle_connect(args)
        elif cmd == "disconnect":
            self.handle_disconnect(args)
        elif cmd == "status":
            self.show_status()
        elif cmd == "help":
            self.show_help()
        else:
            print(f"  Unknown command: {cmd}. Type 'help' for commands.")
    
    def run(self):
        """Run the interactive CLI."""
        self.show_banner()
        self.show_help()
        
        try:
            while self.running:
                try:
                    line = input("mineconnect> ")
                    self.process_command(line)
                except KeyboardInterrupt:
                    print("\n\nUse 'quit' to exit")
                    continue
                except EOFError:
                    break
        finally:
            if self.client:
                self.client.disconnect()
            print("\nGoodbye!\n")


def run_daemon_mode(args):
    """Run in daemon mode with auto-connect."""
    print("Starting MineConnect client in daemon mode...")
    print(f"Domain: {args.domain}")
    
    client = MineConnectClient(domain=args.domain)
    
    # Connect based on flags
    if args.java or args.both:
        client.connect_java(args.java_port)
    if args.bedrock or args.both:
        client.connect_bedrock(args.bedrock_port)
    
    print("Tunnels started. Press Ctrl+C to stop.")
    
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("\n\nShutting down...")
        client.disconnect()
        print("Disconnected.")


def main():
    """Main CLI entry point."""
    parser = argparse.ArgumentParser(
        description="MineConnect Client - Connect to your Minecraft server tunnels"
    )
    parser.add_argument(
        "--domain",
        default="ideadev.me",
        help="Your server domain (default: ideadev.me)"
    )
    parser.add_argument(
        "--interactive",
        "-i",
        action="store_true",
        help="Run in interactive mode with command prompt"
    )
    parser.add_argument(
        "--java",
        action="store_true",
        help="Connect Java Edition tunnel"
    )
    parser.add_argument(
        "--bedrock",
        action="store_true",
        help="Connect Bedrock Edition tunnel"
    )
    parser.add_argument(
        "--both",
        action="store_true",
        help="Connect both tunnels"
    )
    parser.add_argument(
        "--java-port",
        type=int,
        default=25565,
        help="Local Java Edition port (default: 25565)"
    )
    parser.add_argument(
        "--bedrock-port",
        type=int,
        default=19132,
        help="Local Bedrock Edition port (default: 19132)"
    )
    
    args = parser.parse_args()
    
    # Default to interactive if no connection flags specified
    if args.interactive or not (args.java or args.bedrock or args.both):
        cli = InteractiveCLI(domain=args.domain)
        cli.run()
    else:
        run_daemon_mode(args)


if __name__ == "__main__":
    main()
