"""
Status command - Check submission status from the ToRivers API.
"""

from __future__ import annotations

from datetime import datetime
from typing import Any

import httpx
from rich.console import Console
from rich.panel import Panel
from rich.table import Table

from ._config import (
    API_TIMEOUT_SECONDS,
    extract_error_message,
    get_api_base_url,
    get_auth_token,
    is_authenticated,
)

console = Console()

# Status display configuration
STATUS_STYLES = {
    "pending": ("[yellow]Pending[/yellow]", "yellow"),
    "validating": ("[blue]Validating[/blue]", "blue"),
    "validation_failed": ("[red]Validation Failed[/red]", "red"),
    "reviewing": ("[cyan]Under Review[/cyan]", "cyan"),
    "approved": ("[green]Approved[/green]", "green"),
    "rejected": ("[red]Rejected[/red]", "red"),
    "published": ("[green]Published[/green]", "green"),
}


def check_status(submission_id: str | None = None) -> bool:
    """
    Check the status of submitted automations.

    Args:
        submission_id: Optional specific submission ID to check

    Returns:
        True if successful, False otherwise
    """
    if not is_authenticated():
        console.print("[red]Error:[/red] Not authenticated")
        console.print("[dim]Run 'torivers login' to authenticate[/dim]")
        return False

    try:
        token = get_auth_token()
    except RuntimeError as exc:
        console.print(f"[red]Error:[/red] {exc}")
        return False

    console.print(
        Panel.fit(
            "[bold]Submission Status[/bold]",
            subtitle="Checking your automations",
        )
    )
    console.print()

    submissions = _fetch_submissions(token, submission_id)
    if submissions is None:
        return False

    if submission_id:
        if not submissions:
            console.print(f"[red]Error:[/red] Submission '{submission_id}' not found")
            return False
        _display_submission_detail(submissions[0])
        return True

    if not submissions:
        console.print("[dim]No submissions found[/dim]")
        console.print("[dim]Submit an automation with 'torivers submit'[/dim]")
        return True

    _display_submissions_table(submissions)
    return True


def _fetch_submissions(
    token: str,
    submission_id: str | None = None,
) -> list[dict[str, Any]] | None:
    headers = {"Authorization": f"Bearer {token}"}
    api_base_url = get_api_base_url()

    try:
        with httpx.Client(timeout=API_TIMEOUT_SECONDS) as client:
            if submission_id:
                response = client.get(
                    f"{api_base_url}/developer/submissions/{submission_id}",
                    headers=headers,
                )
                if response.status_code == 404:
                    return []
                if response.status_code != 200:
                    error_message = extract_error_message(response)
                    console.print(
                        f"[red]Error:[/red] Failed to fetch submission: {error_message}"
                    )
                    return None
                payload = response.json() if response.content else {}
                return [payload] if isinstance(payload, dict) else []

            response = client.get(
                f"{api_base_url}/developer/submissions",
                params={"limit": 20, "offset": 0},
                headers=headers,
            )
            if response.status_code != 200:
                error_message = extract_error_message(response)
                console.print(
                    f"[red]Error:[/red] Failed to fetch submissions: {error_message}"
                )
                return None

            payload = response.json() if response.content else {}
            if not isinstance(payload, dict):
                return []
            submissions = payload.get("submissions", [])
            return submissions if isinstance(submissions, list) else []
    except httpx.TimeoutException:
        console.print("[red]Error:[/red] Request timed out while fetching status")
        return None
    except httpx.HTTPError as exc:
        console.print(f"[red]Error:[/red] Failed to connect to API: {exc}")
        return None


def _format_timestamp(timestamp: Any, with_seconds: bool = False) -> str:
    if not isinstance(timestamp, str) or not timestamp:
        return "Unknown"
    try:
        dt = datetime.fromisoformat(timestamp.replace("Z", "+00:00"))
    except ValueError:
        return timestamp
    return (
        dt.strftime("%Y-%m-%d %H:%M:%S UTC")
        if with_seconds
        else dt.strftime("%Y-%m-%d %H:%M")
    )


def _display_submissions_table(submissions: list[dict[str, Any]]) -> None:
    """Display submissions in a table."""
    table = Table(title="Your Submissions", show_header=True)
    table.add_column("ID", style="cyan", width=36)
    table.add_column("Automation", width=30)
    table.add_column("Status", width=20)
    table.add_column("Submitted", style="dim", width=20)

    for submission in submissions[:10]:
        status = str(submission.get("status", "unknown"))
        status_display, _ = STATUS_STYLES.get(status, (f"[dim]{status}[/dim]", "dim"))
        automation_name = str(submission.get("automation_name", "unknown"))
        version = str(submission.get("version", "0.0.0"))

        table.add_row(
            str(submission.get("id", "Unknown")),
            f"{automation_name} v{version}",
            status_display,
            _format_timestamp(submission.get("submitted_at")),
        )

    console.print(table)
    if len(submissions) > 10:
        console.print(
            f"\n[dim]Showing 10 of {len(submissions)} submissions. "
            "Use --id to view a specific submission.[/dim]"
        )

    console.print()
    console.print(
        "[dim]Use 'torivers status <submission-id>' for detailed status[/dim]"
    )


def _display_submission_detail(submission: dict[str, Any]) -> None:
    """Display detailed submission information."""
    status = str(submission.get("status", "unknown"))
    status_display, status_color = STATUS_STYLES.get(
        status, (f"[dim]{status}[/dim]", "dim")
    )

    details = [
        f"[bold]Submission ID:[/bold] [cyan]{submission.get('id', 'Unknown')}[/cyan]",
        (
            "[bold]Automation:[/bold] "
            f"{submission.get('automation_name', 'unknown')} "
            f"v{submission.get('version', '0.0.0')}"
        ),
        f"[bold]Status:[/bold] {status_display}",
        f"[bold]Submitted:[/bold] {_format_timestamp(submission.get('submitted_at'), with_seconds=True)}",
    ]

    validated_at = submission.get("validated_at")
    if validated_at:
        details.append(
            f"[bold]Validated:[/bold] {_format_timestamp(validated_at, with_seconds=True)}"
        )

    reviewed_at = submission.get("reviewed_at")
    if reviewed_at:
        details.append(
            f"[bold]Reviewed:[/bold] {_format_timestamp(reviewed_at, with_seconds=True)}"
        )

    validation_score = submission.get("validation_score")
    if validation_score is not None:
        details.append(f"[bold]Validation Score:[/bold] {validation_score}/100")

    ai_review_score = submission.get("ai_review_score")
    if ai_review_score is not None:
        details.append(f"[bold]AI Review Score:[/bold] {ai_review_score}/100")

    review_notes = submission.get("review_notes")
    if isinstance(review_notes, str) and review_notes.strip():
        details.append("")
        details.append("[bold]Review Notes:[/bold]")
        details.append(review_notes.strip())

    validation_errors = submission.get("validation_errors")
    if isinstance(validation_errors, list) and validation_errors:
        details.append("")
        details.append("[red]Validation Errors:[/red]")
        for error in validation_errors[:10]:
            details.append(f"  - {error}")

    validation_warnings = submission.get("validation_warnings")
    if isinstance(validation_warnings, list) and validation_warnings:
        details.append("")
        details.append("[yellow]Validation Warnings:[/yellow]")
        for warning in validation_warnings[:10]:
            details.append(f"  - {warning}")

    if status == "published" and submission.get("published_automation_id"):
        details.append("")
        details.append("[green]Your automation is live in marketplace.[/green]")
        app_url = get_api_base_url().removesuffix("/api")
        details.append(
            "Marketplace URL: "
            f"[cyan]{app_url}/marketplace/{submission['published_automation_id']}[/cyan]"
        )

    console.print(
        Panel(
            "\n".join(details),
            title="Submission Details",
            border_style=status_color,
        )
    )


def list_statuses() -> None:
    """List all possible submission statuses."""
    console.print("[bold]Submission Status Types:[/bold]\n")
    for _, (display, _) in STATUS_STYLES.items():
        console.print(f"  {display}")
    console.print()
