
import shutil
from pathlib import Path
import importlib.resources as pkg_resources

from rich.console import Console
from rich.table import Table

from _yoyo_cli import templates


def get_project_root():
    current = Path.cwd()
    for parent in [current] + list(current.parents):
        if (parent / "main.py").exists() or (parent / ".git").exists():
            return parent
    return current


def init_project(console: Console):
    dst_path = Path.cwd()
    with pkg_resources.path(templates, "project") as template_path:
        shutil.copytree(template_path, dst_path, dirs_exist_ok=True)
        (dst_path / "__init__.py").unlink(missing_ok=True)
        console.print("[green]✅ Project has been created![/green]")


def help_command(console: Console):
    table = Table(title="🛠 Доступные команды YoYoGram CLI", style="magenta")
    table.add_column("Command", style="cyan3", no_wrap=True)
    table.add_column("Arguments", style="deep_sky_blue1")
    table.add_column("Description", style="white")
    table.add_row("init", "", "Create a new project")
    table.add_row("bot", "bot_name", "Create a new bot")
    table.add_row("router", "name Optional:index Optional:bot_name\nProviding bot_name it will create router by tgbot/bots/bot_name/routers/router_name path\nNot providing bot_name, it established router by the current path\nNot providing index means the last position", "Establish a new router")
    console.print(table)


def create_bot(console: Console, bot_name: str):
    with pkg_resources.path(templates, "bot") as template_path:
        bots_dir = get_project_root() / "tgbot" / "bots" / bot_name

        for item in template_path.rglob("*"):
            if item.is_file():
                rel_path = item.relative_to(template_path)
                dst_file = bots_dir / rel_path
                dst_file.parent.mkdir(parents=True, exist_ok=True)

                try:
                    content = item.read_text(encoding="utf-8")
                    content = content.replace("{bot_name}", bot_name)
                    dst_file.write_text(content, encoding="utf-8")
                except UnicodeDecodeError:
                    shutil.copyfile(item, dst_file)

        console.print(f"[green]✅ {bot_name} has been created by tgbot/bots/{bot_name} directory![/green]")


def establish_router(console: Console, router_name: str, router_index: int = -1, bot_name: str = None):
    with pkg_resources.path(templates, "router") as template_path:
        if bot_name:
            bots_dir = get_project_root() / "tgbot" / "bots" / bot_name / "routers" / router_name
        else:
            for parent in [Path.cwd()] + list(Path.cwd().parents):
                if (parent / "routers").exists():
                    bots_dir = parent / "routers" / router_name
                    break
            else:
                bots_dir = get_project_root() / "tgbot" / "bots" / bot_name / "routers" / router_name

        for item in template_path.rglob("*"):
            if item.is_file():
                rel_path = item.relative_to(template_path)
                dst_file = bots_dir / rel_path
                dst_file.parent.mkdir(parents=True, exist_ok=True)
                try:
                    content = item.read_text(encoding="utf-8")
                    content = content.replace("{bot_name}", bot_name)
                    content = content.replace("{router_name}", router_name)
                    content = content.replace("{router_index}", str(router_index))
                    dst_file.write_text(content, encoding="utf-8")
                except UnicodeDecodeError:
                    shutil.copyfile(item, dst_file)

        if bot_name:
            console.print(f"[green]✅ {router_name} has been established by tgbot/bots/{bot_name}/routers/{router_name} directory![/green]")
        else:
            console.print(f"[green]✅ {router_name} has been established by {str(bots_dir)} directory![/green]")
