#!/usr/bin/env bash

# Cyber Valley Tickets - Environment Management Script
# Helper for managing systemd services and viewing logs

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m'

SERVICES="cvland-backend cvland-indexer"
CONTAINERS="cvland-ganache cvland-ipfs cvland-valkey"

usage() {
    echo "Cyber Valley Tickets - Environment Management"
    echo ""
    echo "Usage: ./cvland <command>"
    echo ""
    echo "Commands:"
    echo "  start       Start the full development environment"
    echo "  stop        Stop all systemd services and containers"
    echo "  restart     Restart all services"
    echo "  status      Show status of all services and containers"
    echo "  logs        Show logs from all services (journalctl + podman)"
    echo "  logs -f     Follow logs in real-time"
    echo "  clean       Full reset: stop services, remove DB, clean state"
    echo "  backend     Show backend logs only"
    echo "  frontend    Show frontend logs only"
    echo "  indexer     Show indexer logs only"
    echo ""
    echo "Examples:"
    echo "  ./cvland start          # Start everything"
    echo "  ./cvland logs -f        # Follow all logs"
    echo "  ./cvland status         # Check what's running"
    echo "  ./cvland clean          # Reset everything"
}

show_status() {
    echo -e "${BOLD}${CYAN}=== Systemd Services ===${NC}"
    for svc in $SERVICES; do
        status=$(systemctl --user is-active "$svc" 2>/dev/null || echo "inactive")
        if  "$status" == "active" ; then
            echo -e "  ${GREEN}โ—${NC} $svc"
        else
            echo -e "  ${RED}โ—‹${NC} $svc"
        fi
    done
    
    echo ""
    echo -e "${BOLD}${CYAN}=== Podman Containers ===${NC}"
    for container in $CONTAINERS; do
        if podman ps --format "{{.Names}}" | grep -q "^${container}$"; then
            echo -e "  ${GREEN}โ—${NC} $container"
        else
            echo -e "  ${RED}โ—‹${NC} $container"
        fi
    done
}

show_logs() {
    local follow=""
     "${1:-}" == "-f"  && follow="-f"
    
    echo -e "${YELLOW}Showing logs (Ctrl+C to exit)...${NC}"
    echo -e "${CYAN}Note: Logs from journald (services) and podman (containers)${NC}"
    echo ""
    
    # Combine journalctl and podman logs
    # This is a bit tricky, we'll show them separately
    
    # Create a temp script to show both
    (
        # Systemd services logs
        journalctl --user -u cvland-backend -u cvland-indexer $follow 2>/dev/null &
        JOURNAL_PID=$!
        
        # Podman container logs
        for container in $CONTAINERS; do
            if podman ps --format "{{.Names}}" | grep -q "^${container}$"; then
                podman logs $follow "$container" 2>/dev/null &
            fi
        done
        
        wait $JOURNAL_PID 2>/dev/null || true
    )
}

show_service_logs() {
    local service="$1"
    case "$service" in
        backend)
            journalctl --user -u cvland-backend -f
            ;;
        indexer)
            journalctl --user -u cvland-indexer -f
            ;;
        *)
            echo "Unknown service: $service"
            exit 1
            ;;
    esac
}

stop_all() {
    echo -e "${BLUE}Stopping systemd services...${NC}"
    systemctl --user stop $SERVICES 2>/dev/null || true
    
    echo -e "${BLUE}Stopping podman containers...${NC}"
    for container in $CONTAINERS; do
        podman stop "$container" 2>/dev/null || true
        podman rm "$container" 2>/dev/null || true
    done
    
    echo -e "${GREEN}All services stopped${NC}"
}

clean_all() {
    echo -e "${YELLOW}This will remove the database and reset all state.${NC}"
    read -p "Are you sure? [y/N] " -n 1 -r
    echo
    
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo "Aborted."
        exit 0
    fi
    
    stop_all
    
    echo -e "${BLUE}Removing database...${NC}"
    rm -f "$SCRIPT_DIR/backend/db.sqlite3"
    rm -f "$SCRIPT_DIR/backend/db.sqlite3"-* 2>/dev/null || true
    
    echo -e "${BLUE}Cleaning temporary files...${NC}"
    rm -f /tmp/contract_vars.txt /tmp/deploy_output.log
    
    echo -e "${GREEN}Cleanup complete${NC}"
}

start_all() {
    "$SCRIPT_DIR/run.sh"
}

restart_all() {
    stop_all
    sleep 2
    start_all
}

# Main
case "${1:-}" in
    start)
        start_all
        ;;
    stop)
        stop_all
        ;;
    restart)
        restart_all
        ;;
    status)
        show_status
        ;;
    logs)
        shift
        show_logs "$@"
        ;;
    backend)
        show_service_logs backend
        ;;
    frontend)
        show_service_logs frontend
        ;;
    indexer)
        show_service_logs indexer
        ;;
    clean)
        clean_all
        ;;
    help|--help|-h)
        usage
        ;;
    *)
        echo "Unknown command: ${1:-}"
        echo ""
        usage
        exit 1
        ;;
esac

Graph