import os
import asyncio
import questionary
from rich.console import Console
from rich.text import Text
from textwrap import shorten
from bot.script.bot_script import AresEngine
from .slice_engine import ByTurboSliceEngine

MAX_NAME_LEN = 40
dispatcher = ByTurboSliceEngine()

def truncate(text: str, width: int) -> str:
    return shorten(text, width=width, placeholder="…")

def select_file(console: Console, start_path: str) -> None:
    current_path = os.path.abspath(start_path)
    console.print("\n[bold][green][FILE][/green] Please select a [green].txt[/green] file[/bold]\n")
    while True:
        try:
            term_width = console.size.width - 4
            header = Text(f"[DIR] {current_path}", overflow="fold")
            console.print(header)

            entries = [".."] + os.listdir(current_path)
            entries.sort(
                key=lambda x: (
                    not os.path.isdir(os.path.join(current_path, x)),
                    x.lower(),
                )
            )
            choices = []
            for item in entries:
                full_path = os.path.join(current_path, item)
                if item == "..":
                    choices.append(questionary.Choice("[...]  back", value=".."))
                    continue
                
                name = truncate(item, MAX_NAME_LEN)
                if os.path.isdir(full_path):
                    choices.append(questionary.Choice(f"[DIR] {name}/", value=item))
                else:
                    icon = "[TXT]" if item.endswith(".txt") else "[FILE]"
                    choices.append(questionary.Choice(f"{icon} {name}", value=item))

            selected = questionary.select(
                "select  file --[name.txt]",
                choices=choices,
                instruction="↑↓ navigate • Enter select • Ctrl+C exit",
            ).ask()

            if selected is None:
                return

            selected_path = os.path.join(current_path, selected)

            if os.path.isdir(selected_path):
                current_path = os.path.abspath(selected_path)
                console.print()  # spacing
                continue

            if selected_path.endswith(".txt"):
                console.print(f"\n[bold]✅ File selected:[/bold] [blue]{selected_path}[/blue]\n")
                
                dispatcher.extract_combo_content(selected_path)

                accounts_list = dispatcher.intial_acc_list()
                
                if not accounts_list:
                    console.print("[bold red]❌ The selected file is empty or incorrectly formatted (user:pass).[/bold red]\n")
                    continue

                try:
                    page_url = input(">> Enter Target Url: ")
                    headless = int(input("\n>> Headless --[1/0]: "))
                    threads = int(input("\n>> Enter threads --[number required]:"))
                    
                    bot = AresEngine(page_url, dispatcher, headless, threads)
                except ValueError:
                    console.print("[bold red] invalid input try again")
                
                asyncio.run(bot.run())
                return
            else:
                console.print("[bold red]❌ Only .txt files allowed![/bold red]\n")

        except PermissionError:
            console.print("[red]🚫 Permission denied[/red]\n")
            current_path = os.path.dirname(current_path)