import typer, sys, os, subprocess
from pathlib import Path
from typing import Optional
from rich.console import Console

console = Console()

def logs_command(
    job_id: Optional[str] = typer.Argument(None, help="Job ID to view."),
    tail: bool = typer.Option(False, "--tail", "-f", help="Follow output live."),
    error: bool = typer.Option(False, "--error", "-e", help="View .err log instead of .out")
):
    """View or follow job logs."""
    log_dir = Path("logs")
    if not log_dir.exists():
        console.print("[red]Error: 'logs/' directory not found.[/red]")
        sys.exit(1)

    suffix = ".err" if error else ".out"
    target_file = None

    if job_id:
        matching = list(log_dir.glob(f"*{job_id}{suffix}"))
        if not matching:
             console.print(f"[red]No log found for Job {job_id}[/red]")
             sys.exit(1)
        target_file = matching[0]
    else:
        files = list(log_dir.glob(f"*{suffix}"))
        if not files:
             console.print(f"[yellow]No {suffix} files found.[/yellow]")
             return
        files.sort(key=os.path.getmtime)
        target_file = files[-1]

    console.print(f"[dim]Viewing: {target_file}[/dim]")
    cmd = ["tail", "-f", str(target_file)] if tail else ["cat", str(target_file)]
    
    try:
        subprocess.run(cmd, check=True)
    except KeyboardInterrupt:
        console.print("\n[dim]Stopped.[/dim]")