#!/bin/bash
# CC-ADVANCECYBER CLI
# Enhanced Claude Code with 46 agents, 39 skills, and persistent memory

set -euo pipefail

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

# Colors (CCRouter cyan/teal theme)
CYAN='\033[0;36m'
BOLD_CYAN='\033[1;36m'
DIM_CYAN='\033[2;36m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
WHITE='\033[1;37m'
DIM='\033[2m'
NC='\033[0m'

show_banner() {
    echo ""
    echo -e "${BOLD_CYAN}    ___       __                               _____      __             ${NC}"
    echo -e "${BOLD_CYAN}   /   | ____/ /   ______ _____  ________     / ___/__  __/ /_  ___  _____${NC}"
    echo -e "${BOLD_CYAN}  / /| |/ __  / | / / __ \`/ __ \\/ ___/ _ \\   / /   / / / / __ \\/ _ \\/ ___/${NC}"
    echo -e "${BOLD_CYAN} / ___ / /_/ /| |/ / /_/ / / / / /__/  __/  / /___/ /_/ / /_/ /  __/ /    ${NC}"
    echo -e "${BOLD_CYAN}/_/  |_\\__,_/ |___/\\__,_/_/ /_/\\___/\\___/   \\____/\\__, /_.___/\\___/_/     ${NC}"
    echo -e "${BOLD_CYAN}                                                 /____/                   ${NC}"
    echo ""
    echo -e "${DIM_CYAN}                    46 Agents • 39 Skills • Persistent Memory${NC}"
    echo ""
}

show_banner_large() {
    echo ""
    echo -e "${BOLD_CYAN} █████╗ ██████╗ ██╗   ██╗ █████╗ ███╗   ██╗ ██████╗███████╗ ██████╗██╗   ██╗██████╗ ███████╗██████╗ ${NC}"
    echo -e "${BOLD_CYAN}██╔══██╗██╔══██╗██║   ██║██╔══██╗████╗  ██║██╔════╝██╔════╝██╔════╝╚██╗ ██╔╝██╔══██╗██╔════╝██╔══██╗${NC}"
    echo -e "${BOLD_CYAN}███████║██║  ██║██║   ██║███████║██╔██╗ ██║██║     █████╗  ██║      ╚████╔╝ ██████╔╝█████╗  ██████╔╝${NC}"
    echo -e "${BOLD_CYAN}██╔══██║██║  ██║╚██╗ ██╔╝██╔══██║██║╚██╗██║██║     ██╔══╝  ██║       ╚██╔╝  ██╔══██╗██╔══╝  ██╔══██╗${NC}"
    echo -e "${BOLD_CYAN}██║  ██║██████╔╝ ╚████╔╝ ██║  ██║██║ ╚████║╚██████╗███████╗╚██████╗   ██║   ██████╔╝███████╗██║  ██║${NC}"
    echo -e "${BOLD_CYAN}╚═╝  ╚═╝╚═════╝   ╚═══╝  ╚═╝  ╚═╝╚═╝  ╚═══╝ ╚═════╝╚══════╝ ╚═════╝   ╚═╝   ╚═════╝ ╚══════╝╚═╝  ╚═╝${NC}"
    echo ""
    echo -e "${DIM_CYAN}                            Enterprise Claude Code Distribution${NC}"
    echo ""
}

show_help() {
    show_banner
    echo -e "${WHITE}Usage:${NC} advancecyber [command] [options]"
    echo ""
    echo -e "${WHITE}Commands:${NC}"
    echo -e "    ${CYAN}(none)${NC}          Launch Claude Code with Advancecyber enhancements"
    echo -e "    ${CYAN}install${NC}         Install/update CC-ADVANCECYBER components"
    echo -e "    ${CYAN}doctor${NC}          Check installation health"
    echo -e "    ${CYAN}status${NC}          Show current configuration"
    echo -e "    ${CYAN}agents${NC}          List available agents"
    echo -e "    ${CYAN}skills${NC}          List available skills"
    echo -e "    ${CYAN}memory${NC}          Memory system commands"
    echo -e "    ${CYAN}help${NC}            Show this help message"
    echo ""
    echo -e "${WHITE}Options passed to Claude Code:${NC}"
    echo "    -p, --print     Print response and exit"
    echo "    All other claude options are supported"
    echo ""
    echo -e "${WHITE}Examples:${NC}"
    echo -e "    advancecyber                    ${DIM}# Launch interactive mode${NC}"
    echo -e "    advancecyber -p \"Hello\"         ${DIM}# Quick query${NC}"
    echo -e "    advancecyber doctor             ${DIM}# Health check${NC}"
    echo -e "    advancecyber agents             ${DIM}# List agents${NC}"
    echo ""
    echo -e "${DIM}Documentation: https://advancecyber.ai/docs${NC}"
}

cmd_install() {
    show_banner
    echo -e "${BLUE}Running CC-ADVANCECYBER installer...${NC}"
    "$DIST_DIR/install.sh" "$@"
}

cmd_doctor() {
    show_banner
    echo -e "${WHITE}Health Check${NC}"
    echo ""

    # Check Claude Code
    if command -v claude &> /dev/null; then
        echo -e "  ${GREEN}✓${NC} Claude Code: $(claude --version 2>/dev/null || echo 'installed')"
    else
        echo -e "  ${YELLOW}✗${NC} Claude Code: not found"
    fi

    # Check agents
    local agent_count=$(ls -1 ~/.claude/agents/*.md 2>/dev/null | wc -l | tr -d ' ')
    if [ "$agent_count" -ge 40 ]; then
        echo -e "  ${GREEN}✓${NC} Agents: $agent_count installed"
    else
        echo -e "  ${YELLOW}✗${NC} Agents: $agent_count (expected 46+)"
    fi

    # Check skills
    local skill_count=$(find ~/.claude/skills -mindepth 1 -maxdepth 1 -type d 2>/dev/null | wc -l | tr -d ' ')
    if [ "$skill_count" -ge 30 ]; then
        echo -e "  ${GREEN}✓${NC} Skills: $skill_count installed"
    else
        echo -e "  ${YELLOW}✗${NC} Skills: $skill_count (expected 39+)"
    fi

    # Check Docker
    if command -v docker &> /dev/null && docker info &> /dev/null; then
        echo -e "  ${GREEN}✓${NC} Docker: running"

        # Check memory backend
        if docker ps --format '{{.Names}}' 2>/dev/null | grep -q "qdrant"; then
            echo -e "  ${GREEN}✓${NC} Qdrant: running (port 6334)"
        else
            echo -e "  ${DIM}○${NC} Qdrant: not running"
        fi

        if docker ps --format '{{.Names}}' 2>/dev/null | grep -q "n8n"; then
            echo -e "  ${GREEN}✓${NC} n8n: running (port 5679)"
        else
            echo -e "  ${DIM}○${NC} n8n: not running"
        fi

        if docker ps --format '{{.Names}}' 2>/dev/null | grep -q "claude-postgres\|postgres"; then
            echo -e "  ${GREEN}✓${NC} PostgreSQL: running"
        else
            echo -e "  ${DIM}○${NC} PostgreSQL: not running"
        fi
    else
        echo -e "  ${DIM}○${NC} Docker: not available"
    fi

    # Check Ollama
    if command -v ollama &> /dev/null; then
        echo -e "  ${GREEN}✓${NC} Ollama: installed"
    else
        echo -e "  ${DIM}○${NC} Ollama: not installed"
    fi

    echo ""
}

cmd_status() {
    show_banner
    echo -e "${WHITE}Status${NC}"
    echo ""
    echo -e "  Version:    ${CYAN}$VERSION${NC}"
    echo -e "  Claude Dir: ${DIM}~/.claude${NC}"
    echo -e "  Docker Dir: ${DIM}~/docker/local${NC}"
    echo ""
    cmd_doctor
}

cmd_agents() {
    show_banner
    local count=$(ls -1 ~/.claude/agents/*.md 2>/dev/null | wc -l | tr -d ' ')
    echo -e "${WHITE}Available Agents ($count)${NC}"
    echo ""
    for agent in ~/.claude/agents/*.md; do
        if [ -f "$agent" ]; then
            local name=$(basename "$agent" .md)
            local desc=$(grep -m1 "^description:" "$agent" 2>/dev/null | sed 's/description: *//' | head -c 50)
            printf "  ${CYAN}%-22s${NC} ${DIM}%s${NC}\n" "$name" "${desc}..."
        fi
    done
    echo ""
}

cmd_skills() {
    show_banner
    local count=$(find ~/.claude/skills -mindepth 1 -maxdepth 1 -type d 2>/dev/null | wc -l | tr -d ' ')
    echo -e "${WHITE}Available Skills ($count)${NC}"
    echo ""
    for skill in ~/.claude/skills/*/; do
        if [ -d "$skill" ]; then
            local name=$(basename "$skill")
            printf "  ${CYAN}%s${NC}\n" "$name"
        fi
    done
    echo ""
}

cmd_memory() {
    show_banner
    case "${1:-status}" in
        start)
            echo -e "${WHITE}Starting memory backend...${NC}"
            cd ~/docker/local && docker compose up -d
            ;;
        stop)
            echo -e "${WHITE}Stopping memory backend...${NC}"
            cd ~/docker/local && docker compose down
            ;;
        status)
            echo -e "${WHITE}Memory Backend Status${NC}"
            echo ""
            cd ~/docker/local && docker compose ps 2>/dev/null || echo "  Not configured"
            ;;
        *)
            echo "Usage: advancecyber memory [start|stop|status]"
            ;;
    esac
    echo ""
}

launch_claude() {
    # Show banner
    show_banner_large

    # Show quick tips
    echo -e "${DIM}  ? for shortcuts [advancecyber]${NC}"
    echo ""

    # Launch Claude Code
    exec claude "$@"
}

# Main
main() {
    case "${1:-}" in
        -h|--help|help)
            show_help
            ;;
        install)
            shift
            cmd_install "$@"
            ;;
        doctor)
            cmd_doctor
            ;;
        status)
            cmd_status
            ;;
        agents)
            cmd_agents
            ;;
        skills)
            cmd_skills
            ;;
        memory)
            shift
            cmd_memory "$@"
            ;;
        "")
            # No args - show banner and launch Claude Code
            launch_claude
            ;;
        *)
            # Pass through to claude with banner
            show_banner
            exec claude "$@"
            ;;
    esac
}

main "$@"
