"""Status command - List and filter tasks."""

from datetime import datetime
from typing import Optional

import click
from rich.table import Table

from flow import Flow
from flow.errors import AuthenticationError

from .base import BaseCommand, console
from .utils import get_status_style


class StatusCommand(BaseCommand):
    """List tasks with optional filtering."""

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

    @property
    def help(self) -> str:
        return "List tasks with optional filtering"

    def get_command(self) -> click.Command:
        @click.command(name=self.name, help=self.help)
        @click.option("--all", "show_all", is_flag=True, help="Show all tasks (default: last 24h)")
        @click.option(
            "--status",
            type=click.Choice(["pending", "running", "completed", "failed", "cancelled"]),
            help="Filter by status",
        )
        @click.option("--limit", default=20, help="Maximum number of tasks to show")
        def status(show_all: bool, status: Optional[str], limit: int):
            """List recent tasks.

            By default shows tasks from the last 24 hours. Use --all to see all tasks.

            \b
            Examples:
                flow status                    # Recent tasks
                flow status --all              # All tasks
                flow status --status running   # Only running tasks
                flow status --limit 5          # Show only 5 tasks
            """
            self._execute(show_all, status, limit)

        return status

    def _execute(self, show_all: bool, status: Optional[str], limit: int) -> None:
        """Execute the status command."""
        try:
            flow_client = Flow()

            # Get tasks with filters
            tasks = flow_client.list(all_time=show_all, status=status, limit=limit)

            if not tasks:
                console.print("No tasks found")
                return

            # Create table
            table = Table(title=f"Tasks (showing up to {limit})")
            table.add_column("Task ID", style="cyan")
            table.add_column("Status", justify="center")
            table.add_column("Instance", style="blue")
            table.add_column("Created", style="dim")
            table.add_column("Runtime", justify="right", style="dim")

            for task in tasks:
                # Format status with color
                status_style = get_status_style(task.state)
                status_text = f"[{status_style}]{task.state}[/{status_style}]"

                # Format created time
                created = task.created_at
                if isinstance(created, str):
                    created = datetime.fromisoformat(created.replace("Z", "+00:00"))
                created_str = created.strftime("%Y-%m-%d %H:%M")

                # Calculate runtime
                runtime = ""
                if task.started_at and task.state == "running":
                    started = task.started_at
                    if isinstance(started, str):
                        started = datetime.fromisoformat(started.replace("Z", "+00:00"))
                    duration = datetime.utcnow() - started
                    hours = int(duration.total_seconds() // 3600)
                    minutes = int((duration.total_seconds() % 3600) // 60)
                    runtime = f"{hours}h {minutes}m"
                elif task.runtime_seconds:
                    hours = int(task.runtime_seconds // 3600)
                    minutes = int((task.runtime_seconds % 3600) // 60)
                    runtime = f"{hours}h {minutes}m"

                table.add_row(
                    task.id,
                    status_text,
                    task.instance_type or "N/A",
                    created_str,
                    runtime,
                )

            console.print(table)

            # Show summary
            if len(tasks) == limit:
                console.print(f"\n[dim]Showing first {limit} tasks. Use --limit to see more.[/dim]")

        except AuthenticationError:
            self.handle_auth_error()
        except Exception as e:
            self.handle_error(str(e))


# Export command instance
command = StatusCommand()
