#!/bin/bash

SERVICE=$1
MODE=$2

# EN: Check usage
# VI: Kiểm tra cách sử dụng
if [ -z "$SERVICE" ]; then
    echo "Usage: $0 <service-name>"
    echo "Example: $0 iam-service"
    echo "Example: $0 mission-service-net"
    exit 1
fi

if [ "$SERVICE" = "docker" ]; then
    # Legacy support: ./logs.sh docker <name>
    CONTAINER=$2
    if [ -z "$CONTAINER" ]; then
        docker ps --format "{{.Names}}"
        exit 1
    fi
    docker logs -f "$CONTAINER"
    exit 0
fi

# Smart Detection
# Try to find a docker container that Matches or Contains the service name
# Common prefixes/suffixes: -local, goodgo-, etc.

# 1. Exact match
if docker ps --format "{{.Names}}" | grep -q "^${SERVICE}$"; then
    echo "📦 Found exact container match. Tailing logs..."
    docker logs -f "$SERVICE"
    exit 0
fi

# 2. Local suffix match (e.g. service-name-local, -net-local)
SUFFIX_MATCH="${SERVICE}-local"
if docker ps --format "{{.Names}}" | grep -q "${SUFFIX_MATCH}"; then
    echo "📦 Found container: $SUFFIX_MATCH"
    docker logs -f "$SUFFIX_MATCH"
    exit 0
fi

# 3. Fuzzy match (head -n 1)
FUZZY=$(docker ps --format "{{.Names}}" | grep "$SERVICE" | head -n 1)
if [ -n "$FUZZY" ]; then
    echo "📦 Found fuzzy match: $FUZZY"
    docker logs -f "$FUZZY"
    exit 0
fi

# 4. If no docker container found, and it's a Node app, maybe user wants pnpm log?
# But typically we don't use this script for local pnpm unless wrapped.
echo "❌ No running container found for $SERVICE."
echo "   If you are running it locally (non-Docker), check the terminal window where you started it."
