"""delete-host command — delete all data for a host (admin operation)."""

from __future__ import annotations

import asyncio

import typer
from rich.console import Console
from sqlalchemy.exc import OperationalError

from cli_framework import get_context
from session_hub_cli.cli import app
from session_hub_cli.commands._helpers import get_query_api
from session_hub_cli.context import SessionHubContext


@app.command("delete-host")
def delete_host(
    ctx: typer.Context,
    hostname: str = typer.Argument(..., help="Host whose data to delete"),
    force: bool = typer.Option(False, "--force", help="Skip the interactive confirmation"),
) -> None:
    """Delete all data for a host (admin operation)."""
    app_ctx = get_context(ctx)
    assert isinstance(app_ctx, SessionHubContext)
    console = app_ctx.console
    if not force:
        typer.confirm(
            f"Delete all data for host '{hostname}'? This cannot be undone.",
            default=False,
            abort=True,
        )
    try:
        deleted = asyncio.run(_delete(console, hostname))
    except OperationalError as exc:
        console.print(f"[red]Error:[/red] Cannot connect to PostgreSQL: {exc}")
        raise typer.Exit(1) from None
    console.print(f"Deleted {deleted} sessions for host '{hostname}'")


async def _delete(console: Console, hostname: str) -> int:
    api = get_query_api(console)
    try:
        return await api.delete_host_data(hostname)
    finally:
        await api.close()
