import stat
from pathlib import Path

from rich.progress import Progress, SpinnerColumn, TextColumn

from casoar.models import Hooks


def write_hooks(hooks: Hooks, hooks_folder: Path | str = Path("./git/hooks")) -> None:
    if isinstance(hooks_folder, str):
        hooks_folder = Path(hooks_folder)
    if not hooks_folder.exists():
        hooks_folder.mkdir(parents=True)

    for hook_type, commands in hooks:
        if len(commands) == 0:
            continue

        with Progress(
            SpinnerColumn(),
            TextColumn("[progress.description]{task.description}"),
        ) as progress:
            task = progress.add_task(description=f"Writing {hook_type} hook", total=1)

            hook_path = hooks_folder / hook_type

            file_content = (
                "#!/bin/bash\n"
                "# This file was automatically generated by captain-hook\n"
            )
            if hooks.virtual_env is not None:
                file_content += f"source {hooks.virtual_env}/bin/activate\n"

            for command in commands:
                file_content += f"{command.to_bash_string()}\n"

            hook_path.write_text(file_content)

            hook_path.chmod(hook_path.stat().st_mode | stat.S_IEXEC)

            progress.update(
                task, completed=1, description=f"Writing {hook_type} hook ✅"
            )
