#!/bin/bash
# Copyright (c) Advanced Micro Devices, Inc., or its affiliates.
# SPDX-License-Identifier: MIT

# CK Status - Check container status and information

set -e
set -o pipefail

# Find script directory and load common utilities
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${SCRIPT_DIR}/common.sh"

# Initialize configuration
PROJECT_ROOT=$(get_project_root "${SCRIPT_DIR}")
CONTAINER_NAME=$(get_container_name "${PROJECT_ROOT}")

# Help message
show_help() {
    cat << EOF
CK Status - Check container status and information

Usage: ck-status [options] [container_name]

Options:
  -h, --help              Show this help message
  --name <name>           Specify container name
  --all                   Show all CK containers
  -v, --verbose           Show detailed information

Arguments:
  container_name          Optional container name (default: ck_<username>_<branch>)

Environment:
  CK_CONTAINER_NAME - Override default container name

Examples:
  ck-status                    # Check default container status
  ck-status my_container       # Check specific container
  ck-status --all              # Show all CK containers
  ck-status -v                 # Show detailed information

EOF
}

# Parse arguments
show_all=false
verbose=false

while [[ $# -gt 0 ]]; do
    case $1 in
        -h|--help)
            show_help
            exit 0
            ;;
        --name)
            CONTAINER_NAME="$2"
            shift 2
            ;;
        --all)
            show_all=true
            shift
            ;;
        -v|--verbose)
            verbose=true
            shift
            ;;
        *)
            CONTAINER_NAME="$1"
            shift
            ;;
    esac
done

DOCKER_IMAGE=$(get_docker_image)

# Show all containers
if [ "$show_all" = true ]; then
    echo "Composable Kernel Docker Containers:"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

    username=$(get_username)
    containers=$(docker ps -a --filter "name=ck_${username}_" --format "table {{.Names}}\t{{.Status}}\t{{.CreatedAt}}" 2>/dev/null || echo "")

    if [ -z "$containers" ] || [ "$containers" = "NAMES	STATUS	CREATED AT" ]; then
        echo "No CK containers found for user '${username}'"
    else
        echo "$containers"
    fi
    exit 0
fi

# Check specific container status
echo "Container: ${CONTAINER_NAME}"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

if container_is_running "${CONTAINER_NAME}"; then
    echo "Status: RUNNING ✓"
    echo ""
    docker ps --filter "name=^${CONTAINER_NAME}$" --format "table {{.Names}}\t{{.Status}}\t{{.Image}}"

    if [ "$verbose" = true ]; then
        echo ""
        echo "Container Details:"
        echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
        docker inspect "${CONTAINER_NAME}" --format '
Image: {{.Config.Image}}
Created: {{.Created}}
Platform: {{.Platform}}
Mounts: {{range .Mounts}}
  - {{.Source}} -> {{.Destination}}{{end}}
'
    fi

    echo ""
    echo "GPU Information:"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    docker exec "${CONTAINER_NAME}" bash -c "rocm-smi --showproductname 2>/dev/null | head -10 || echo 'No GPU detected'"

    if [ "$verbose" = true ]; then
        echo ""
        echo "GPU Target:"
        gpu_target=$(detect_gpu_target "${CONTAINER_NAME}")
        echo "  ${gpu_target}"

        echo ""
        echo "Build Status:"
        echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
        if docker exec "${CONTAINER_NAME}" test -d /workspace/build 2>/dev/null; then
            if docker exec "${CONTAINER_NAME}" test -f /workspace/build/build.ninja 2>/dev/null; then
                echo "  CMake configured ✓"
                echo "  Build directory: /workspace/build"

                # Count built test binaries
                bin_count=$(docker exec "${CONTAINER_NAME}" bash -c "ls -1 /workspace/build/bin 2>/dev/null | wc -l" || echo "0")
                echo "  Test binaries: ${bin_count}"
            else
                echo "  CMake not configured"
            fi
        else
            echo "  Build directory not found"
        fi
    fi

elif container_exists "${CONTAINER_NAME}"; then
    echo "Status: STOPPED"
    echo ""
    echo "Start with: ck-start"
else
    echo "Status: DOES NOT EXIST"
    echo ""
    echo "Create with: ck-start"
fi
