"""Logs command for viewing task output.

Provides both historical log retrieval and real-time streaming.
Supports stdout/stderr selection and tail functionality.

Examples:
    View recent logs:
        $ flow logs task-abc123

    Stream logs in real-time:
        $ flow logs task-abc123 -f

    Show last 50 lines of stderr:
        $ flow logs task-abc123 --stderr -n 50
"""

import sys

import click

from flow import Flow
from flow.errors import FlowError

from .base import BaseCommand, console


class LogsCommand(BaseCommand):
    """Logs command implementation.
    
    Handles both batch retrieval and streaming modes with automatic
    reconnection for long-running tasks.
    """

    @property
    def name(self) -> str:
        return "logs"

    @property
    def help(self) -> str:
        return "Get logs from a running task"

    def get_command(self) -> click.Command:
        @click.command(name=self.name, help=self.help)
        @click.argument("task_id")
        @click.option("--follow", "-f", is_flag=True, help="Follow log output")
        @click.option("--tail", "-n", type=int, default=100, help="Number of lines to show")
        @click.option("--stderr", is_flag=True, help="Show stderr instead of stdout")
        def logs(task_id: str, follow: bool, tail: int, stderr: bool):
            """Get logs from a running task."""
            self._execute(task_id, follow, tail, stderr)

        return logs

    def _execute(self, task_id: str, follow: bool, tail: int, stderr: bool) -> None:
        """Execute log retrieval or streaming.
        
        Args:
            task_id: Task identifier to get logs from
            follow: Enable real-time streaming mode
            tail: Number of lines to show (batch mode only)
            stderr: Show stderr instead of stdout
            
        Raises:
            FlowError: If task not found or logs unavailable
            SystemExit: On error
        """
        try:
            client = Flow(auto_init=True)

            if follow:
                console.print(f"[dim]Following logs for task {task_id}... (Ctrl+C to stop)[/dim]\n")
                try:
                    for line in client.logs(task_id, follow=True, stderr=stderr):
                        console.print(line, end="")
                except KeyboardInterrupt:
                    console.print("\n[dim]Stopped following logs[/dim]")
            else:
                logs = client.logs(task_id, tail=tail, stderr=stderr)
                if logs:
                    console.print(logs)
                else:
                    console.print(f"[dim]No logs available for task {task_id}[/dim]")

        except FlowError as e:
            console.print(f"[red]✗ Error:[/red] {e}")
            sys.exit(1)


# Export command instance
command = LogsCommand()
