import shutil, sys, subprocess
from rich.console import Console
from rich.table import Table
from rich import box
from jazari.utils import get_current_user  # We will move helper functions to utils.py later

console = Console()

def status_command():
    if not shutil.which("squeue"):
        console.print("[bold red]Error:[/bold red] 'squeue' command not found.")
        console.print("Are you running this on a Slurm login node?")
        sys.exit(1)

    user = get_current_user()

    squeue_cmd = ["squeue", "-u", user, "-h", "-o", "%i|%j|%T|%M|%D|%R"]

    try:
        result       = subprocess.run(squeue_cmd, check=True, capture_output=True, text=True)
        output_lines = result.stdout.strip().split('\n')
        output_lines = [line for line in output_lines if line.strip()]

        if not output_lines:
             console.print(f"\n[dim]No active jobs found for user: [bold]{user}[/bold][/dim]\n")
             return

        table = Table(
            title        = f"🐘 Cluster Activity for user: [bold green]{user}[/bold green]",
            box          = box.ROUNDED,
            header_style = "bold blue",
            expand       = True
        )
        table.add_column("Job ID", style="cyan", no_wrap=True)
        table.add_column("Name")
        table.add_column("State")
        table.add_column("Time Used", justify="right")
        table.add_column("Nodes", justify="right")
        table.add_column("Nodelist / Reason", style="dim")

        for line in output_lines:
            try:
                job_id, name, state, time_used, nodes, reason = line.split('|')

                # Color-code the state
                if state == "RUNNING":
                    state_formatted = f"[bold green]{state}[/bold green]"
                elif state == "PENDING":
                    state_formatted = f"[yellow]{state}[/yellow]"
                else:
                    state_formatted = f"[red]{state}[/red]"

                table.add_row(job_id, name, state_formatted, time_used, nodes, reason)
            except ValueError:
                continue

        console.print(table)

    except subprocess.CalledProcessError as e:
         console.print(f"[bold red]Error running squeue:[/bold red] {e.stderr}")