"""
Status CLI command
Shows status of all services and networks
"""

import sys
from ..core.docker import DockerManager
from ..core.config import Config


def print_status():
    """Print all services status"""
    print("\n" + "=" * 60)
    print("INFRA SERVICES STATUS")
    print("=" * 60)

    # Check Docker
    if not DockerManager.check_docker():
        print("\n✗ Docker: Not running")
        sys.exit(1)

    print("\n✓ Docker: Running")

    # Networks
    print("\nNETWORKS:")
    print("-" * 60)
    print(f"{'Network':<20} {'Status':<15} {'Containers':<10}")
    print("-" * 60)

    for network in Config.NETWORKS:
        status = DockerManager.get_network_status(network)
        if status["exists"]:
            status_str = "✓ Created"
            containers = status["container_count"]
        else:
            status_str = "✗ Not created"
            containers = 0

        print(f"{network:<20} {status_str:<15} {containers:<10}")

    # Services
    print("\nSERVICES:")
    print("-" * 60)
    print(f"{'Service':<25} {'Status':<15} {'Uptime':<20} {'Ports':<20}")
    print("-" * 60)

    running = 0
    stopped = 0
    not_created = 0

    for service in Config.get_managed_services():
        status = DockerManager.get_container_status(service)

        if status["status"] == "running":
            status_symbol = "● Running"
            running += 1
        elif status["status"] == "stopped":
            status_symbol = "○ Stopped"
            stopped += 1
        else:
            status_symbol = "✗ Not created"
            not_created += 1

        uptime = status["uptime"] or "-"
        ports = ", ".join(status["ports"][:2]) if status["ports"] else "-"
        if len(status["ports"]) > 2:
            ports += f" (+{len(status['ports']) - 2} more)"

        # Use full service name (e.g., "project/dev")
        print(f"{service:<25} {status_symbol:<15} {uptime:<20} {ports:<20}")

    # Summary
    total = running + stopped + not_created
    print("\n" + "-" * 60)
    print(f"Total: {total} | Running: {running} | Stopped: {stopped} | Not created: {not_created}")
    print("=" * 60)


def main():
    """Main entry point for status command"""
    if len(sys.argv) > 1 and sys.argv[1] in ["-h", "--help"]:
        print("Usage: infra status")
        print("\nShow status of all infra services and networks")
        sys.exit(0)

    print_status()


if __name__ == "__main__":
    main()
