import typer, shutil, sys, subprocess
from rich.console import Console
from rich.prompt import Confirm
from typing import Optional
from jazari.utils import get_current_user

console = Console()

def kill_command(
        job_id: Optional[str] = typer.Argument(None, help = 'Job ID to cancel.'),
        cancel_all: bool = typer.Option(False, '--all', help = 'Cancel ALL active jobs.')
):
    if not shutil.which("scancel"):
        console.print("[bold red]Error:[/bold red] 'scancel' command not found.")
        console.print("Are you running this on a Slurm login node?")
        sys.exit(1)
    
    user = get_current_user()

    if cancel_all:
        if not Confirm.ask(f"[bold red]⚠️  DANGER:[/bold red] Cancel ALL jobs for '{user}'?"):
             sys.exit(0)
        subprocess.run(["scancel", "-u", user], check=True)
        console.print(f"[bold green]💥 All jobs cancelled.[/bold green]")
        return

    if job_id:
        subprocess.run(["scancel", job_id], check=True)
        console.print(f"[bold green]💥 Signal sent to cancel job {job_id}.[/bold green]")
        return

    console.print("[yellow]Usage: jazari kill <JOB_ID> or jazari kill --all[/yellow]")