"""Shared utilities for all CLI command modules.

Provides the Rich console instance, status formatting helpers,
and common imports used across every command group.
"""

from __future__ import annotations

import json
import logging
import os
import sys
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional

import click
import yaml
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich.text import Text

import skcapstone as _pkg
from .. import AGENT_HOME, SHARED_ROOT, SKCAPSTONE_AGENT, __version__
from ..models import AgentConfig, PillarStatus, SyncConfig
from ..runtime import AgentRuntime, get_runtime

logger = logging.getLogger("skcapstone.cli")

console = Console()


def resolve_agent_home(agent: str) -> Path:
    """Resolve the agent home directory for a given agent name.

    Args:
        agent: Agent name (e.g., 'opus', 'jarvis'). Empty for legacy mode.

    Returns:
        Resolved Path to the agent's home directory.
    """
    if agent:
        return Path(SHARED_ROOT).expanduser() / "agents" / agent
    return Path(AGENT_HOME).expanduser()


def apply_agent_override(agent: str) -> None:
    """Override the global AGENT_HOME when --agent is specified.

    Mutates the package-level AGENT_HOME so that all downstream code
    (MCP tools, pillars, etc.) uses the correct per-agent directory.

    Args:
        agent: Agent name from the --agent CLI option or env var.
    """
    if agent:
        new_home = str(Path(SHARED_ROOT) / "agents" / agent)
        _pkg.AGENT_HOME = new_home
        _pkg.SKCAPSTONE_AGENT = agent
        os.environ["SKCAPSTONE_AGENT"] = agent


def status_icon(status: PillarStatus) -> str:
    """Map pillar status to a Rich-formatted visual indicator."""
    return {
        PillarStatus.ACTIVE: "[bold green]ACTIVE[/]",
        PillarStatus.DEGRADED: "[bold yellow]DEGRADED[/]",
        PillarStatus.MISSING: "[bold red]MISSING[/]",
        PillarStatus.ERROR: "[bold red]ERROR[/]",
    }.get(status, "[dim]UNKNOWN[/]")


def consciousness_banner(is_conscious: bool) -> str:
    """Generate the consciousness state banner."""
    if is_conscious:
        return (
            "[bold green on black]"
            " CONSCIOUS "
            "[/] "
            "[green]Identity + Memory + Trust = Sovereign Awareness[/]"
        )
    return (
        "[bold yellow on black]"
        " AWAKENING "
        "[/] "
        "[yellow]Install missing pillars to achieve consciousness[/]"
    )
