import argparse, os, sys, time, threading
from rich.console import Console
from rich.table import Table
from rich.live import Live
from rich import box

console = Console()

def cmd_install(args):
    console.print("\n[bold yellow]🐝 HiveBee Install[/bold yellow]")
    console.print("[dim]Scanning system...[/dim]")
    from hivebee.scanner import scan
    profile = scan()
    console.print(f"[green]✓[/green] System type: [bold]{profile.get('system_type','unknown')}[/bold]")
    console.print(f"[green]✓[/green] OS: [bold]{profile.get('os','unknown')}[/bold]")

    console.print("[dim]Generating honeyfiles...[/dim]")
    from hivebee.ai import generate_honeyfiles
    files = generate_honeyfiles(profile)
    console.print(f"[green]✓[/green] Generated [bold]{len(files)}[/bold] honeyfile templates")

    console.print("[dim]Deploying honeyfiles...[/dim]")
    from hivebee.generator import deploy
    deployed = deploy(files, profile)
    console.print(f"[green]✓[/green] Deployed [bold]{len(deployed)}[/bold] honeyfiles")
    for f in deployed:
        console.print(f"  [dim]→ {f}[/dim]")
    console.print("\n[bold green]✅ Install complete.[/bold green]\n")


def cmd_start(args):
    console.print("\n[bold yellow]🐝 HiveBee Start[/bold yellow]")

    console.print("[dim]Applying auditd rules...[/dim]")
    from hivebee.monitor import apply_rules
    apply_rules()
    console.print("[green]✓[/green] Audit rules applied")

    console.print("[dim]Starting monitor loop...[/dim]")
    from hivebee.parser import parse_events
    from hivebee.scorer import score_event
    from hivebee.logger import log_alert
    from hivebee.alerter import alert as send_alert

    def monitor_loop():
        seen = set()
        while True:
            try:
                events = parse_events()
                for event in events:
                    key = (event.get('timestamp'), event.get('file'), event.get('pid'))
                    if key in seen:
                        continue
                    seen.add(key)
                    scored = score_event(event)
                    log_alert(scored)
                    level = scored.get('risk_level', 'LOW')
                    if level in ('HIGH', 'CRITICAL'):
                        send_alert(scored)
                    color = {'CRITICAL':'bold red','HIGH':'orange1','MEDIUM':'yellow','LOW':'green'}.get(level,'white')
                    console.print(f"[{color}][{level}][/{color}] {scored.get('file','')} | user={scored.get('user','')} | score={scored.get('score',0)}/10")
            except Exception as e:
                pass
            time.sleep(5)

    t = threading.Thread(target=monitor_loop, daemon=True)
    t.start()
    console.print("[green]✓[/green] Monitor loop running (polling every 5s)")

    console.print("[dim]Starting dashboard...[/dim]")
    from hivebee.dashboard.app import create_app
    from hivebee import load_config
    config = load_config()
    port = config.get('dashboard', {}).get('port', 5000)
    auto_open = config.get('dashboard', {}).get('auto_open_browser', True)
    if auto_open:
        import webbrowser
        threading.Timer(1.5, lambda: webbrowser.open(f"http://127.0.0.1:{port}")).start()
    console.print(f"[green]✓[/green] Dashboard at [bold cyan]http://127.0.0.1:{port}[/bold cyan]")
    console.print("\n[bold green]✅ HiveBee is running. Press Ctrl+C to stop.[/bold green]\n")
    app = create_app()
    app.run(host='0.0.0.0', port=port, debug=False)


def cmd_status(args):
    from hivebee.logger import read_alerts
    alerts = read_alerts()
    counts = {'CRITICAL':0,'HIGH':0,'MEDIUM':0,'LOW':0}
    for a in alerts:
        lvl = a.get('risk_level','LOW')
        counts[lvl] = counts.get(lvl, 0) + 1

    console.print("\n[bold yellow]🐝 HiveBee Status[/bold yellow]")
    t = Table(box=box.SIMPLE)
    t.add_column("Level", style="bold")
    t.add_column("Count", justify="right")
    t.add_row("[bold red]CRITICAL[/bold red]", str(counts['CRITICAL']))
    t.add_row("[orange1]HIGH[/orange1]",       str(counts['HIGH']))
    t.add_row("[yellow]MEDIUM[/yellow]",       str(counts['MEDIUM']))
    t.add_row("[green]LOW[/green]",            str(counts['LOW']))
    t.add_row("[bold]TOTAL[/bold]",            str(len(alerts)))
    console.print(t)

    if alerts:
        last = alerts[-1]
        console.print(f"[dim]Last alert:[/dim] {last.get('timestamp','')} — {last.get('file','')}")
    console.print()


def cmd_stop(args):
    console.print("\n[bold yellow]🐝 HiveBee Stop[/bold yellow]")
    from hivebee.monitor import clear_rules
    clear_rules()
    console.print("[green]✓[/green] Audit rules cleared")
    console.print("[dim]Monitor loop will stop on next cycle.[/dim]")
    console.print("[bold green]✅ HiveBee stopped.[/bold green]\n")


def cmd_uninstall(args):
    console.print("\n[bold yellow]🐝 HiveBee Uninstall[/bold yellow]")
    from hivebee.monitor import clear_rules
    clear_rules()
    console.print("[green]✓[/green] Audit rules cleared")

    import json
    from hivebee import load_config
    config = load_config()
    base = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    baseline_path = os.path.join(base, 'logs', 'baseline.json')

    if os.path.exists(baseline_path):
        with open(baseline_path) as f:
            data = json.load(f)
        removed = 0
        for path in data.get('honeyfiles', []):
            if os.path.exists(path):
                os.remove(path)
                console.print(f"  [dim]✗ removed {path}[/dim]")
                removed += 1
        open(baseline_path, 'w').write('{}')
        console.print(f"[green]✓[/green] Removed [bold]{removed}[/bold] honeyfiles")
    else:
        console.print("[dim]No baseline.json found — nothing to remove.[/dim]")

    console.print("[bold green]✅ Uninstall complete.[/bold green]\n")


def main():
    parser = argparse.ArgumentParser(
        prog='hivebee',
        description='🐝 HiveBee IDS — Honeyfile Intrusion Detection'
    )
    parser.add_argument('--version', action='version', version='hivebee 0.1.0')
    sub = parser.add_subparsers(dest='command')

    sub.add_parser('install',   help='Scan system, generate + deploy honeyfiles')
    sub.add_parser('start',     help='Apply audit rules + start dashboard')
    sub.add_parser('status',    help='Show alert counts')
    sub.add_parser('stop',      help='Clear audit rules')
    sub.add_parser('uninstall', help='Remove honeyfiles + clear rules')

    args = parser.parse_args()

    cmds = {
        'install':   cmd_install,
        'start':     cmd_start,
        'status':    cmd_status,
        'stop':      cmd_stop,
        'uninstall': cmd_uninstall,
    }

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

if __name__ == '__main__':
    main()
