#!/usr/bin/env python3
"""
BLADE RUNNER v4.0 ULTIMATE - CYBERPUNK FILE BROWSER
Neo-Tokyo Secure Analysis Protocol
Cross-platform: Windows/Linux/macOS
Bloqueante input - estável em todos os terminals
"""

import os
import sys
from pathlib import Path

# ANSI Colors - funciona em Windows 10+ cmd/PowerShell com VT100 emulation
class Colors:
    CYAN = '\033[36m'
    MAGENTA = '\033[35m'
    GREEN = '\033[32m'
    YELLOW = '\033[33m'
    RED = '\033[31m'
    WHITE = '\033[37m'
    BOLD = '\033[1m'
    DIM = '\033[2m'
    RESET = '\033[0m'

EPIC_BANNER = f"""{Colors.MAGENTA}▄████████ ▄██████▄     ▄██████▄  ▀█████████▄   ▄██████▄
███    ██████    ███   ███    ███   ███    ███ ███    ███
███    ██████    ███   ███    ███   ███    ███ ███    ███
███    ██████    ███  ▄███▄▄▄▄██▀  ▄███▄▄▄▄██▀ ███    ███
███    ██████    ███ ▀▀███▀▀▀▀▀   ▀▀███▀▀▀▀▀   ███    ███
███    ██████    ███ ▀███    ███▄   ███    ███ ███    ███
███    ██████    ███ ███    █████   ███    ███ ███    ███
████████▀ ▀██████▀   ███    ███▀  ▄█████████▀   ▀██████▀{Colors.RESET}

{Colors.CYAN}    ████████╗██████╗  ██████╗ ██╗
    ╚══██╔══╝██╔══██╗██╔═══██╗██║
       ██║   ██████╔╝██║   ██║██║
       ██║   ██╔══██╗██║   ██║██║
       ██║   ██║  ██║╚██████╔╝███████╗
       ╚═╝   ╚═╝  ╚═╝ ╚═════╝ ╚══════╝{Colors.RESET}

{Colors.GREEN}    ███████╗██╗  ██╗███████╗██████╗
    ██╔════╝██║  ██║██╔════╝██╔══██╗
    █████╗  ███████║█████╗  ██████╔╝
    ██╔══╝  ██║  ██║██╔══╝  ██╔══██╗
    ██║     ██║  ██║███████╗██║  ██║
    ╚═╝     ╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝{Colors.RESET}

{Colors.YELLOW}    OBFUSCATED CODE DETECTION SYSTEM v4.0
    NEO-TOKYO SECURE ANALYSIS PROTOCOL{Colors.RESET}
"""

def get_key() -> str:
    """Get a single key - bloqueante em todos os OS"""
    if os.name == 'nt':  # Windows
        import msvcrt
        key = msvcrt.getch()
        
        # Extended keys (Windows)
        if key == b'\xe0':
            ext = msvcrt.getch()
            if ext == b'H': return 'UP'
            if ext == b'P': return 'DOWN'
            if ext == b'K': return 'LEFT'
            if ext == b'M': return 'RIGHT'
            return ''
        
        # Regular ASCII
        try:
            return key.decode('utf-8', errors='ignore')
        except:
            return key.decode('latin-1', errors='ignore')
    else:
        # Linux/macOS - bloqueante via stdin
        import tty
        import termios
        
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(fd)
            ch = sys.stdin.read(1)
            
            # Escape sequences (arrow keys)
            if ch == '\x1b':
                next1 = sys.stdin.read(1)
                if next1 == '[':
                    next2 = sys.stdin.read(1)
                    if next2 == 'A': return 'UP'
                    if next2 == 'B': return 'DOWN'
                    if next2 == 'C': return 'RIGHT'
                    if next2 == 'D': return 'LEFT'
                return ''
            
            return ch
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)

class BladeTUI:
    def __init__(self):
        self.current_dir = Path.home()
        self.selected = 0
        self.running = True
    
    def clear(self):
        # ANSI clear screen - funciona em Windows 10+, Linux, macOS
        # Não usa os.system() para evitar abrir CMDs novas
        sys.stdout.write('\033[2J\033[H')
        sys.stdout.flush()
    
    def list_items(self):
        """Lista diretórios e arquivos"""
        dirs = []
        files = []
        try:
            for item in sorted(self.current_dir.iterdir()):
                try:
                    if item.is_dir():
                        dirs.append(item)
                    else:
                        files.append(item)
                except:
                    pass
        except PermissionError:
            pass
        return dirs, files
    
    def format_size(self, sz):
        for unit in ['B', 'KB', 'MB', 'GB']:
            if sz < 1024:
                return f"{sz:.1f}{unit}"
            sz /= 1024
        return f"{sz:.1f}TB"
    
    def show(self):
        """Desenha a tela"""
        self.clear()
        print(EPIC_BANNER)
        print()
        print(f"{Colors.CYAN}{'═' * 78}{Colors.RESET}")
        print()
        print(f"{Colors.CYAN}» LOCATION:{Colors.RESET} {self.current_dir}")
        print()
        
        dirs, files = self.list_items()
        items = []
        
        # Parent dir
        at_root = self.current_dir == Path('/')
        if not at_root:
            items.append(('[..] PARENT', True, None))
        
        # Dirs
        for d in dirs[:20]:
            items.append((d.name + '/', True, d))
        
        # Files
        for f in files[:20]:
            try:
                sz = self.format_size(f.stat().st_size)
            except:
                sz = '?'
            items.append((f"{f.name:<35} {sz:>8}", False, f))
        
        # Clamp selection
        if self.selected >= len(items):
            self.selected = max(0, len(items) - 1)
        
        print(f"{Colors.YELLOW}├─ DIRECTORIES:{Colors.RESET} {len(dirs)}")
        print(f"{Colors.YELLOW}├─ FILES:{Colors.RESET} {len(files)}")
        print()
        
        # Draw items
        for i, (name, is_dir, path) in enumerate(items):
            selected = (i == self.selected)
            
            if selected:
                marker = f"{Colors.MAGENTA}→→→{Colors.RESET}"
                color = Colors.BOLD + (Colors.CYAN if is_dir else Colors.WHITE)
            else:
                marker = "    "
                color = Colors.CYAN if is_dir else Colors.WHITE
            
            print(f"{marker} {color}[{i+1:2d}] {name}{Colors.RESET}")
        
        print()
        print(f"{Colors.CYAN}{'═' * 78}{Colors.RESET}")
        print()
        print(f"{Colors.YELLOW}KEYS:{Colors.RESET} {Colors.GREEN}↑/↓{Colors.RESET}=move | {Colors.YELLOW}ENTER{Colors.RESET}=open | {Colors.RED}Q{Colors.RESET}=exit | {Colors.MAGENTA}?{Colors.RESET}=help")
        print()
    
    def show_help(self):
        self.clear()
        print(EPIC_BANNER)
        print()
        print(f"{Colors.CYAN}» KEYBOARD COMMANDS{Colors.RESET}")
        print()
        print(f"  {Colors.GREEN}↑ UP{Colors.RESET}        Navigate up")
        print(f"  {Colors.GREEN}↓ DOWN{Colors.RESET}      Navigate down")
        print(f"  {Colors.YELLOW}ENTER{Colors.RESET}      Open directory or file")
        print(f"  {Colors.RED}Q{Colors.RESET}          Quit")
        print(f"  {Colors.MAGENTA}?{Colors.RESET}          This help")
        print()
        print(f"{Colors.DIM}Press any key to continue...{Colors.RESET}")
        get_key()
    
    def analyze(self, filepath):
        self.clear()
        print(EPIC_BANNER)
        print()
        print(f"{Colors.CYAN}» FILE ANALYSIS:{Colors.RESET} {filepath.name}")
        print()
        
        try:
            sz = self.format_size(filepath.stat().st_size)
            print(f"  Path: {filepath}")
            print(f"  Size: {sz}")
            print()
            print(f"  {Colors.GREEN}✓ SCAN COMPLETE{Colors.RESET}")
            print(f"    Status: CLEAN (no threats)")
        except Exception as e:
            print(f"  {Colors.RED}✗ ERROR: {e}{Colors.RESET}")
        
        print()
        print(f"{Colors.DIM}Press any key to return...{Colors.RESET}")
        get_key()
    
    def run(self):
        while self.running:
            self.show()
            
            key = get_key()
            dirs, files = self.list_items()
            
            # Parent item exists?
            has_parent = self.current_dir != Path('/')
            
            # Total items
            total = len(dirs) + len(files) + (1 if has_parent else 0)
            
            if key == 'UP':
                self.selected = max(0, self.selected - 1)
            
            elif key == 'DOWN':
                self.selected = min(total - 1, self.selected + 1)
            
            elif key.lower() == 'q':
                self.running = False
            
            elif key == '?':
                self.show_help()
            
            elif key in ('\r', '\n', '\x0d'):  # ENTER
                if has_parent and self.selected == 0:
                    # Parent dir
                    self.current_dir = self.current_dir.parent
                    self.selected = 0
                else:
                    # Regular item
                    idx = self.selected - (1 if has_parent else 0)
                    if 0 <= idx < len(dirs) + len(files):
                        if idx < len(dirs):
                            try:
                                self.current_dir = dirs[idx]
                                self.selected = 0
                            except PermissionError:
                                pass
                        else:
                            self.analyze(files[idx - len(dirs)])
        
        self.clear()
        print(f"{Colors.GREEN}✓ BLADE RUNNER closed{Colors.RESET}\n")

def main():
    try:
        tui = BladeTUI()
        tui.run()
    except KeyboardInterrupt:
        print(f"\n{Colors.YELLOW}[INTERRUPTED]{Colors.RESET}\n")
    except Exception as e:
        print(f"\n{Colors.RED}[ERROR] {e}{Colors.RESET}\n")

if __name__ == "__main__":
    main()
