"""
CLI commands for backup operations.
"""

from typing import Optional, cast

import click

from konigle import models
from konigle.cli.main import cli, get_client
from konigle.filters.website import BackupFilters
from konigle.models.website.backup import Backup


@cli.group()
def backups() -> None:
    """Backup management commands."""
    pass


@backups.command("list")
@click.option("--page", "-p", default=1, help="Page number (default: 1)")
@click.option(
    "--page-size", "-s", default=10, help="Items per page (default: 10)"
)
@click.option(
    "--kind",
    "-k",
    type=click.Choice(["transient", "durable"], case_sensitive=False),
    help="Filter by backup kind",
)
@click.option(
    "--backup-type",
    "-t",
    type=click.Choice(
        [
            "page",
            "folder",
            "blog",
            "product",
            "site_template",
            "site_foundation",
        ],
        case_sensitive=False,
    ),
    help="Filter by backup type",
)
@click.option(
    "--target-id",
    help="Filter by target ID (Page, Folder, Blog, Product ID)",
)
@click.option(
    "--status",
    type=click.Choice(
        ["in_progress", "completed", "failed"], case_sensitive=False
    ),
    help="Filter by backup status",
)
@click.option(
    "--ordering",
    "-o",
    type=click.Choice(["created_at", "-created_at"], case_sensitive=False),
    help="Order by created_at (use - prefix for descending)",
)
@click.pass_context
def list_backups(
    ctx: click.Context,
    page: int,
    page_size: int,
    kind: Optional[str],
    backup_type: Optional[str],
    target_id: Optional[str],
    status: Optional[str],
    ordering: Optional[str],
) -> None:
    """List backups."""
    try:
        client = get_client(ctx.obj["api_key"], ctx.obj["base_url"])

        filters = BackupFilters(
            kind=kind,  # type: ignore
            backup_type=backup_type,  # type: ignore
            target_id=target_id,
            status=status,  # type: ignore
            ordering=ordering,  # type: ignore
        )

        result = client.backups.list(
            page=page, page_size=page_size, filters=filters
        )

        if not result.payload:
            click.echo("No backups found.")
            return

        click.echo(f"Backups (page {page}/{result.num_pages}):")
        click.echo(f"Total: {result.count}")
        click.echo()

        for backup_item in result.payload:
            click.echo(backup_item)

    except Exception as e:
        click.echo(f"✗ Error listing backups: {e}", err=True)
        ctx.exit(1)


@backups.command()
@click.option(
    "--backup-type",
    "-t",
    required=True,
    type=click.Choice(
        [
            "page",
            "folder",
            "blog",
            "product",
            "site_template",
            "site_foundation",
        ],
        case_sensitive=False,
    ),
    help="Type of resource to backup",
)
@click.option(
    "--target-id",
    help=(
        "ID of the resource to backup (Page, Folder, Blog, Product). "
        "Omit for site-level backups (site_template, site_foundation)"
    ),
)
@click.option(
    "--description",
    "-d",
    default="",
    help="Optional description of the backup",
)
@click.option(
    "--trigger",
    type=click.Choice(
        ["manual", "auto_pre_edit", "auto_pre_publish", "scheduled"],
        case_sensitive=False,
    ),
    default="manual",
    help="Trigger type (default: manual)",
)
@click.pass_context
def create(
    ctx: click.Context,
    backup_type: str,
    target_id: Optional[str],
    description: str,
    trigger: str,
) -> None:
    """Create a new backup."""
    try:
        client = get_client(ctx.obj["api_key"], ctx.obj["base_url"])

        backup_data = models.BackupCreate(
            backup_type=backup_type,  # type: ignore
            target_id=target_id,
            description=description,
            trigger=trigger,  # type: ignore
        )

        result = cast(Backup, client.backups.create(backup_data))

        click.echo("✓ Backup created successfully!")
        click.echo(f"ID: {result.id}")
        click.echo(f"Type: {result.backup_type}")
        click.echo(f"Status: {result.status}")
        if result.target_description:
            click.echo(f"Target: {result.target_description}")
        click.echo(f"Created: {result.created_at}")

    except Exception as e:
        click.echo(f"✗ Error creating backup: {e}", err=True)
        ctx.exit(1)


@backups.command()
@click.argument("backup_id")
@click.option("--yes", "-y", is_flag=True, help="Skip confirmation")
@click.pass_context
def delete(
    ctx: click.Context,
    backup_id: str,
    yes: bool,
) -> None:
    """Delete a backup."""
    if not yes:
        if not click.confirm(
            f"Are you sure you want to delete backup {backup_id}?"
        ):
            click.echo("Cancelled.")
            return

    try:
        client = get_client(ctx.obj["api_key"], ctx.obj["base_url"])
        client.backups.delete(backup_id)

        click.echo(f"✓ Backup {backup_id} deleted successfully!")

    except Exception as e:
        click.echo(f"✗ Error deleting backup: {e}", err=True)
        ctx.exit(1)


@backups.command()
@click.argument("backup_id")
@click.option("--yes", "-y", is_flag=True, help="Skip confirmation")
@click.pass_context
def restore(ctx: click.Context, backup_id: str, yes: bool) -> None:
    """Restore a backup."""
    if not yes:
        if not click.confirm(
            f"Are you sure you want to restore backup {backup_id}? "
            "This will overwrite the current version."
        ):
            click.echo("Cancelled.")
            return

    try:
        client = get_client(ctx.obj["api_key"], ctx.obj["base_url"])
        result = client.backups.restore(backup_id)

        click.echo(f"✓ Backup {backup_id} restoration started!")
        click.echo(f"Status: {result.get('status', 'unknown')}")

    except Exception as e:
        click.echo(f"✗ Error restoring backup: {e}", err=True)
        ctx.exit(1)
