"""Core sub-app: status, logs, restart. Uses core_lifecycle and common."""

import subprocess

import typer

from rich.rule import Rule

from armorer.cli import common as cli_common
from armorer.cli import core_lifecycle as cli_lifecycle


def get_core_app() -> typer.Typer:
    core_app = typer.Typer(help="Manage the Armorer Core Service")

    @core_app.command("status")
    def core_status():
        result = subprocess.run(
            ["docker", "ps", "-a", "--filter", "name=armorer-core", "--format", "{{.Status}}"],
            capture_output=True, text=True,
        )
        status = (result.stdout or "").strip()
        cli_common.console.print(Rule("Armorer Core Status", style="cyan"))
        if not status:
            cli_common.console.print("[yellow]Core is not installed.[/yellow]")
        else:
            cli_common.console.print(
                f"{'[green]● Active[/green]' if 'Up' in status else '[red]○ Inactive[/red]'} ({status})"
            )

    @core_app.command("logs")
    def core_logs():
        subprocess.run(["docker", "logs", "--tail", "50", "-f", "armorer-core"])

    @core_app.command("restart")
    def core_restart():
        subprocess.run(["docker", "rm", "-f", "armorer-core"], capture_output=True)
        cli_lifecycle.ensure_armorer_core()

    return core_app
