#!/usr/bin/env bash
# AGENT-K - Multi-Agent Claude Code Terminal Suite
# Main entry point CLI

set -euo pipefail

# =============================================================================
# INITIALIZATION
# =============================================================================

_AGENTK_SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
export AGENTK_ROOT="$_AGENTK_SCRIPT_DIR"

# Source libraries (use AGENTK_ROOT to avoid variable scope issues)
source "$AGENTK_ROOT/lib/core.sh"
source "$AGENTK_ROOT/lib/ui.sh"
source "$AGENTK_ROOT/lib/ipc.sh"
source "$AGENTK_ROOT/lib/spawn.sh"

# =============================================================================
# CONFIGURATION
# =============================================================================

# Default mode
AGENTK_MODE="${AGENTK_MODE:-dev}"
VISUAL_MODE=false
ONE_SHOT=false
ONE_SHOT_PROMPT=""
FOCUSED_AGENT=""

# =============================================================================
# USAGE
# =============================================================================

show_usage() {
    cat <<EOF
${BOLD}AGENT-K${RESET} - Multi-Agent Claude Code Terminal Suite

${BOLD}USAGE:${RESET}
    agentk                          Start interactive session (dev mode)
    agentk --mode ml                Start ML research & training mode
    agentk --visual                 Start with tmux visual panels
    agentk -c "prompt"              One-shot mode (run task, exit)

${BOLD}OPTIONS:${RESET}
    -m, --mode <mode>               Set mode: dev (default) or ml
    -v, --visual                    Enable tmux visual mode
    -c, --command <prompt>          Run single command and exit
    -h, --help                      Show this help message
    --version                       Show version

${BOLD}SESSION COMMANDS:${RESET}
    /status                         Show all agent states
    /logs <agent>                   View agent output
    /kill <agent|all>               Stop agent(s)
    /focus <agent>                  Talk directly to agent
    /unfocus                        Return to orchestrator
    /visual                         Toggle tmux view
    /clear                          Clear screen
    /help                           Show commands
    /exit                           End session

${BOLD}SCOUT COMMANDS:${RESET}
    /search <query>                 Web search
    /github <query>                 Search GitHub
    /papers <topic>                 Search papers (ML mode)
    /libs <task>                    Find libraries
    /sota <topic>                   State-of-the-art

${BOLD}ML MODE COMMANDS:${RESET}
    /experiment <name>              Start experiment
    /metrics                        Show metrics
    /tensorboard                    Open TensorBoard
    /huggingface <query>            Search HF Hub

${BOLD}EXAMPLES:${RESET}
    agentk                          # Start dev mode chat
    agentk --mode ml                # Start ML mode
    agentk -c "Build a REST API"    # One-shot task

EOF
}

show_version() {
    echo "AGENT-K v${AGENTK_VERSION}"
}

# =============================================================================
# ARGUMENT PARSING
# =============================================================================

parse_args() {
    while [[ $# -gt 0 ]]; do
        case "$1" in
            -m|--mode)
                AGENTK_MODE="$2"
                shift 2
                ;;
            -v|--visual)
                VISUAL_MODE=true
                shift
                ;;
            -c|--command)
                ONE_SHOT=true
                ONE_SHOT_PROMPT="$2"
                shift 2
                ;;
            -h|--help)
                show_usage
                exit 0
                ;;
            --version)
                show_version
                exit 0
                ;;
            *)
                log_error "Unknown option: $1"
                show_usage
                exit 1
                ;;
        esac
    done

    # Validate mode
    if [[ "$AGENTK_MODE" != "dev" && "$AGENTK_MODE" != "ml" ]]; then
        log_error "Invalid mode: $AGENTK_MODE (must be 'dev' or 'ml')"
        exit 1
    fi

    export AGENTK_MODE
}

# =============================================================================
# SESSION COMMANDS
# =============================================================================

handle_command() {
    local cmd="$1"
    local args="${2:-}"

    case "$cmd" in
        /status)
            cmd_status
            ;;
        /logs)
            cmd_logs "$args"
            ;;
        /kill)
            cmd_kill "$args"
            ;;
        /focus)
            cmd_focus "$args"
            ;;
        /unfocus)
            cmd_unfocus
            ;;
        /visual)
            cmd_visual
            ;;
        /clear)
            clear_screen
            print_banner
            print_mode_banner "$AGENTK_MODE"
            ;;
        /help)
            print_command_help
            print_scout_commands
            [[ "$AGENTK_MODE" == "ml" ]] && print_ml_commands
            ;;
        /exit|/quit)
            cmd_exit
            ;;
        /search|/github|/papers|/libs|/sota|/huggingface)
            cmd_scout "$cmd" "$args"
            ;;
        /experiment|/metrics|/tensorboard|/checkpoint|/compare)
            cmd_ml "$cmd" "$args"
            ;;
        *)
            print_error "Unknown command: $cmd"
            echo "Type /help for available commands"
            ;;
    esac
}

cmd_status() {
    print_section "Agent Status"

    local agents
    case "$AGENTK_MODE" in
        dev) agents="orchestrator engineer tester security scout" ;;
        ml)  agents="orchestrator researcher ml-engineer data-engineer evaluator scout" ;;
    esac

    for agent in $agents; do
        local status
        status=$(get_agent_status "$agent")
        local message=""
        local task_id
        task_id=$(_get_agent_task "$agent" 2>/dev/null || echo "")

        if [[ -n "$task_id" ]]; then
            message=$(get_task_field "$task_id" "prompt" 2>/dev/null | head -c 40)
            [[ ${#message} -eq 40 ]] && message="${message}..."
        fi

        print_agent_status "$agent" "$status" "$message"
    done
    echo
}

cmd_logs() {
    local agent="$1"

    if [[ -z "$agent" ]]; then
        print_error "Usage: /logs <agent>"
        return
    fi

    print_section "Logs: $agent"
    view_agent_log "$agent" 30
}

cmd_kill() {
    local target="$1"

    if [[ -z "$target" ]]; then
        print_error "Usage: /kill <agent|all>"
        return
    fi

    if [[ "$target" == "all" ]]; then
        kill_all_agents
        print_success "All agents stopped"
    else
        kill_agent "$target"
        print_success "Agent $target stopped"
    fi
}

cmd_focus() {
    local agent="$1"

    if [[ -z "$agent" ]]; then
        print_error "Usage: /focus <agent>"
        return
    fi

    FOCUSED_AGENT="$agent"
    print_info "Now talking directly to: $agent"
    echo "${DIM}Type /unfocus to return to orchestrator${RESET}"
}

cmd_unfocus() {
    if [[ -z "$FOCUSED_AGENT" ]]; then
        print_info "Not focused on any agent"
        return
    fi

    print_info "Returning to orchestrator"
    FOCUSED_AGENT=""
}

cmd_visual() {
    if ! command -v tmux &>/dev/null; then
        print_error "tmux is not installed. Install with: brew install tmux"
        return
    fi

    if [[ "$VISUAL_MODE" == "true" ]]; then
        print_info "Disabling visual mode..."
        VISUAL_MODE=false
        # Would detach from tmux here
    else
        print_info "Enabling visual mode..."
        VISUAL_MODE=true
        start_visual_mode
    fi
}

cmd_exit() {
    print_info "Ending session..."
    end_session
    kill_all_agents
    echo
    echo "${GREEN}Goodbye!${RESET}"
    exit 0
}

cmd_scout() {
    local cmd="$1"
    local query="$2"

    if [[ -z "$query" ]]; then
        print_error "Usage: $cmd <query>"
        return
    fi

    local scout_task="$cmd: $query"
    print_info "Scout is searching..."

    # Create task for scout
    local task_id
    task_id=$(create_task "" "research" "scout" "$scout_task" 1)

    # Spawn scout agent
    spawn_agent "scout" "$task_id" "$AGENTK_MODE"

    # Wait for result
    print_info "Waiting for Scout..."
    watch_task "$task_id" 120

    # Display result
    local result_file
    result_file=$(get_result_file "$task_id")
    if [[ -f "$result_file" ]]; then
        local output
        output=$(jq -r '.output' "$result_file")
        echo
        echo "$output"
    fi
}

cmd_ml() {
    local cmd="$1"
    local args="$2"

    if [[ "$AGENTK_MODE" != "ml" ]]; then
        print_error "ML commands only available in ML mode. Use: agentk --mode ml"
        return
    fi

    case "$cmd" in
        /experiment)
            print_info "Starting experiment: $args"
            # Would create experiment directory and tracking
            ;;
        /metrics)
            print_info "Current metrics:"
            # Would display training metrics
            ;;
        /tensorboard)
            print_info "Opening TensorBoard..."
            tensorboard --logdir="$AGENTK_WORKSPACE/experiments" &
            ;;
        *)
            print_error "ML command not implemented: $cmd"
            ;;
    esac
}

# =============================================================================
# VISUAL MODE (TMUX)
# =============================================================================

start_visual_mode() {
    source "$SCRIPT_DIR/lib/visual.sh" 2>/dev/null || {
        print_error "Visual mode library not found"
        VISUAL_MODE=false
        return
    }

    setup_tmux_session "$AGENTK_MODE"
}

# =============================================================================
# INTERACTIVE LOOP
# =============================================================================

run_interactive() {
    # Initialize workspace
    ensure_workspace
    check_dependencies

    # Create session
    create_session

    # Print banner
    clear_screen
    print_banner
    print_mode_banner "$AGENTK_MODE"

    echo "Type your request or /help for commands."
    echo

    # Main loop
    while true; do
        # Show prompt
        if [[ -n "$FOCUSED_AGENT" ]]; then
            print_focus_prompt "$FOCUSED_AGENT"
        else
            print_user_prompt
        fi

        # Read input with readline support
        local input
        if ! read -r -e input; then
            # EOF (Ctrl+D)
            echo
            cmd_exit
        fi

        # Skip empty input
        [[ -z "$input" ]] && continue

        # Add to history
        history -s "$input"

        # Check for command
        if [[ "$input" == /* ]]; then
            local cmd="${input%% *}"
            local args="${input#* }"
            [[ "$cmd" == "$args" ]] && args=""
            handle_command "$cmd" "$args"
            continue
        fi

        # Regular input - send to orchestrator (or focused agent)
        local target_agent="${FOCUSED_AGENT:-orchestrator}"

        echo
        print_orchestrator_message "Analyzing task..."

        # Create task
        local task_id
        task_id=$(create_task "" "analyze" "$target_agent" "$input" 1)

        # For now, spawn the agent interactively
        spawn_agent_interactive "$target_agent" "$AGENTK_MODE" "$input"

        echo
    done
}

# =============================================================================
# ONE-SHOT MODE
# =============================================================================

run_one_shot() {
    local prompt="$1"

    # Initialize
    ensure_workspace
    check_dependencies
    create_session

    print_banner
    print_mode_banner "$AGENTK_MODE"
    print_task "$prompt"

    # Create task for orchestrator
    local task_id
    task_id=$(create_task "" "orchestrate" "orchestrator" "$prompt" 1)

    # Spawn orchestrator interactively
    spawn_agent_interactive "orchestrator" "$AGENTK_MODE" "$prompt"

    # Cleanup
    end_session
}

# =============================================================================
# MAIN
# =============================================================================

main() {
    parse_args "$@"

    # Check if running in visual mode from start
    if [[ "$VISUAL_MODE" == "true" ]]; then
        start_visual_mode
    fi

    # One-shot or interactive
    if [[ "$ONE_SHOT" == "true" ]]; then
        run_one_shot "$ONE_SHOT_PROMPT"
    else
        run_interactive
    fi
}

# Run
main "$@"
