import os
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from rich.console import Console
from rich.panel import Panel
from rich.syntax import Syntax
from rich.table import Table
from rich.prompt import Prompt
from rich import box
from ana_assistant.skills.cybersecurity import CyberTools
import re

console = Console()


class CyberUI:
    TOOLS = {
        "scan": "port_scan",
        "ping": "ping_host",
        "dns": "dns_lookup",
        "reverse": "reverse_dns",
        "checkdns": "check_dns",
        "subnet": "subnet_calc",
        "headers": "http_headers",
        "ssl": "ssl_check",
        "mac": "mac_lookup",
        "hash": "hash_type",
        "base64": "base64_encode",
        "base64d": "base64_decode",
        "hex": "hex_encode",
        "hexd": "hex_decode",
        "url": "url_encode",
        "urld": "url_decode",
        "whois": "whois_lookup",
        "geoip": "geoip_lookup",
        "myip": "get_public_ip",
        "localip": "get_local_ip",
    }

    def __init__(self):
        self.cyber = CyberTools()
        self.console = Console()

    def show_menu(self):
        table = Table(title="CyberSec Tools", box=box.ROUNDED, show_header=True)
        table.add_column("Command", style="cyan", no_wrap=True)
        table.add_column("Description")

        tools_list = [
            ("scan <host> <ports>", "Port scan (e.g., scan localhost 1-1000)"),
            ("ping <host>", "Ping host"),
            ("dns <domain>", "DNS lookup"),
            ("reverse <ip>", "Reverse DNS lookup"),
            ("checkdns <domain>", "Check DNS records"),
            ("subnet <ip/cidr>", "Subnet calculator"),
            ("headers <url>", "HTTP headers"),
            ("ssl <host>", "SSL certificate check"),
            ("mac <mac>", "MAC address lookup"),
            ("hash <hash>", "Identify hash type"),
            ("base64 <text>", "Base64 encode"),
            ("base64d <text>", "Base64 decode"),
            ("hex <text>", "Hex encode"),
            ("hexd <hex>", "Hex decode"),
            ("url <text>", "URL encode"),
            ("urld <text>", "URL decode"),
            ("whois <domain>", "WHOIS lookup"),
            ("geoip <ip>", "Geolocation lookup"),
            ("myip", "Get public IP"),
            ("localip", "Get local IP"),
            ("net", "Network status"),
            ("help", "Show this menu"),
            ("exit", "Back to main"),
        ]

        for cmd, desc in tools_list:
            table.add_row(cmd, desc)

        self.console.print(table)

    def run(self):
        self.console.print(
            Panel.fit(
                "[bold red]╔══════════════════════════════════════╗[/bold red]\n"
                "[bold red]║[bold]     CYBERSECURITY TOOLS MODE      [bold red]║[/bold red]\n"
                "[bold red]╚══════════════════════════════════════╝[/bold red]",
                border_style="red",
            )
        )
        self.show_menu()

        while True:
            try:
                user_input = self.console.input("\n[red]CyberSec >[/red] ").strip()

                if not user_input:
                    continue

                if user_input.lower() in ["exit", "back", "quit"]:
                    self.console.print("[yellow]Returning to main...[/yellow]")
                    break

                if user_input.lower() == "help":
                    self.show_menu()
                    continue

                if user_input.lower() == "net":
                    self._show_network_status()
                    continue

                self._execute_command(user_input)

            except (EOFError, KeyboardInterrupt):
                break

    def _show_network_status(self):
        table = Table(title="Network Status", box=box.ROUNDED)
        table.add_column("Property", style="cyan")
        table.add_column("Value")

        internet = self.cyber.check_internet()
        local_ip = self.cyber.get_local_ip()
        public_ip = self.cyber.get_public_ip()

        table.add_row("Internet", internet)
        table.add_row("Local IP", local_ip)
        table.add_row("Public IP", public_ip)

        self.console.print(table)

    def _execute_command(self, user_input):
        parts = user_input.split(maxsplit=1)
        cmd = parts[0].lower()
        arg = parts[1] if len(parts) > 1 else ""

        if cmd in self.TOOLS:
            tool_name = self.TOOLS[cmd]
            tool_func = getattr(self.cyber, tool_name)

            try:
                if arg:
                    result = tool_func(arg)
                else:
                    result = tool_func()

                if cmd in ["base64", "base64d", "hex", "hexd", "url", "urld"]:
                    self.console.print(
                        Panel(
                            result,
                            title=f"[cyan]{cmd.upper()} Result[/cyan]",
                            border_style="green",
                        )
                    )
                else:
                    self.console.print(
                        Panel(
                            result,
                            title=f"[cyan]{cmd.upper()} Result[/cyan]",
                            border_style="cyan",
                        )
                    )
            except Exception as e:
                self.console.print(f"[red]Error:[/red] {str(e)}")
        else:
            self.console.print(f"[red]Unknown command:[/red] {cmd}")
            self.console.print("[dim]Type 'help' for available commands[/dim]")


if __name__ == "__main__":
    cyber = CyberUI()
    cyber.run()
