#!/bin/bash

set -e

# Colors for output
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# Source the dependency checker
source "$(dirname "$0")/claudefsd-check-dependencies"

# Function to get saved editor preference
get_saved_editor() {
    if [ -f ~/.claudefsd ]; then
        grep "^editor=" ~/.claudefsd | cut -d'=' -f2
    fi
}

# Function to save editor preference
save_editor_preference() {
    echo "editor=$1" > ~/.claudefsd
}

# Function to determine default choice based on existing docs
get_default_choice() {
    # Use find_brief_file function to check for BRIEF.md
    source "$(dirname "$0")/claudefsd-find-brief"
    if ! find_brief_file >/dev/null 2>&1; then
        echo "0"
    elif [ ! -f docs/REQUIREMENTS.md ] && [ ! -f docs/QUESTIONS.md ]; then
        echo "1"  # Interactive interview
    elif [ -f docs/REQUIREMENTS.md ] && [ ! -f docs/PLAN.md ]; then
        echo "2"  # Create plan from requirements
    elif [ -f docs/QUESTIONS.md ] && [ ! -f docs/PLAN.md ]; then
        echo "2"  # Create plan from questions
    else
        echo "3"  # Development mode
    fi
}

# Function to display the menu
show_menu() {
    echo -e "${GREEN}🤖 Claude Full Self Drive (FSD) Tool${NC}"
    echo
    echo "This tool helps you manage development projects using AI agents."
    echo "Think of it as your AI-powered development team on autopilot!"
    echo
    echo "What would you like to do?"
    echo
    
    local default_choice=$(get_default_choice)
    
    # Check for BRIEF.md using find_brief_file
    source "$(dirname "$0")/claudefsd-find-brief"
    if ! find_brief_file >/dev/null 2>&1; then
        echo "  0) Create project brief - Start your project with a BRIEF.md file"
    fi
    
    # Check if we should show new or old interview flow
    if [ -f docs/INTERVIEW-SESSION.json ]; then
        local session_status=$(jq -r '.status' docs/INTERVIEW-SESSION.json 2>/dev/null || echo "unknown")
        if [ "$session_status" = "in_progress" ]; then
            echo "  1) Interview - Resume existing interview session"
        else
            echo "  1) Interview - Gather requirements through expert Q&A"
        fi
    else
        echo "  1) Interview - Gather requirements through expert Q&A"
    fi
    
    # Show create plan option based on what exists
    if [ -f docs/REQUIREMENTS.md ]; then
        echo "  2) Create plan - Generate development plan from requirements"
    elif [ -f docs/QUESTIONS.md ]; then
        echo "  2) Create plan - Generate plan from answered questions"
    else
        echo "  2) [Requires interview first]"
    fi
    
    echo "  3) Development - Run automated development"
    echo "  4) Exit"
    echo
    
    # Show status of required files
    echo "Current status:"
    source "$(dirname "$0")/claudefsd-find-brief"
    local brief_file=$(find_brief_file 2>/dev/null || echo "")
    if [ -n "$brief_file" ]; then
        echo "  ✓ $brief_file exists"
    else
        echo "  ✗ BRIEF.md missing"
    fi
    
    # Show interview session status if exists
    if [ -f docs/INTERVIEW-SESSION.json ]; then
        local session_status=$(jq -r '.status' docs/INTERVIEW-SESSION.json 2>/dev/null || echo "unknown")
        local total_questions=$(jq -r '.question_count.total' docs/INTERVIEW-SESSION.json 2>/dev/null || echo "0")
        echo "  📝 Interview session: $session_status ($total_questions questions)"
    fi
    
    [ -f docs/REQUIREMENTS.md ] && echo "  ✓ docs/REQUIREMENTS.md exists" || echo "  ✗ docs/REQUIREMENTS.md missing"
    [ -f docs/QUESTIONS.md ] && echo "  ✓ docs/QUESTIONS.md exists" || echo "  ✗ docs/QUESTIONS.md missing"
    [ -f docs/PLAN.md ] && echo "  ✓ docs/PLAN.md exists" || echo "  ✗ docs/PLAN.md missing"
    echo
}

# Function to open file with editor
open_with_editor() {
    local file="$1"
    local editor_choice="$2"
    local saved_editor=$(get_saved_editor)
    
    # If no editor choice provided and we have a saved preference, use it
    if [ -z "$editor_choice" ] && [ -n "$saved_editor" ]; then
        editor_choice=$saved_editor
    fi
    
    # If still no editor choice, prompt
    if [ -z "$editor_choice" ]; then
        echo "What editor would you like to use?"
        echo "  1) nano (default)"
        echo "  2) vim"
        echo "  3) code (VS Code)"
        echo "  4) cursor"
        echo "  5) other"
        echo
        read -p "Enter your choice [1]: " editor_choice
        editor_choice=${editor_choice:-1}
    fi
    
    case $editor_choice in
        1|""|nano)
            save_editor_preference "nano"
            nano "$file"
            ;;
        2|vim)
            save_editor_preference "vim"
            vim "$file"
            ;;
        3|code)
            save_editor_preference "code"
            code . && sleep 2 && code "$file"
            echo "Opening in VS Code. Please edit the file, then press Enter to continue..."
            read -n 1 -s
            ;;
        4|cursor)
            save_editor_preference "cursor"
            cursor . && sleep 2 && cursor "$file"
            echo "Opening in Cursor. Please edit the file, then press Enter to continue..."
            read -n 1 -s
            ;;
        5|other)
            read -p "Enter editor command: " custom_editor
            save_editor_preference "$custom_editor"
            $custom_editor "$file"
            echo "Please edit the file, then press Enter to continue..."
            read -n 1 -s
            ;;
        *)
            # Use the saved editor as a command
            save_editor_preference "$editor_choice"
            $editor_choice "$file"
            echo "Please edit the file, then press Enter to continue..."
            read -n 1 -s
            ;;
    esac
}

# Check dependencies first
check_dependencies

# Function to check for updates and auto-update if needed
check_for_updates() {
    # Only check if we can reach npm registry quickly
    if timeout 2 npm view claude-fsd version >/dev/null 2>&1; then
        local current_version=$(npm list -g claude-fsd --depth=0 2>/dev/null | grep claude-fsd | sed 's/.*@//' | sed 's/ ->.*//')
        local latest_version=$(timeout 2 npm view claude-fsd version 2>/dev/null)
        
        if [ -n "$current_version" ] && [ -n "$latest_version" ] && [ "$current_version" != "$latest_version" ]; then
            echo -e "${YELLOW}📦 Update available: claude-fsd $current_version → $latest_version${NC}"
            echo -e "${GREEN}🔄 Auto-updating claude-fsd...${NC}"
            
            # Attempt automatic update
            if npm update -g claude-fsd >/dev/null 2>&1; then
                echo -e "${GREEN}✅ Successfully updated to claude-fsd $latest_version${NC}"
                echo
            else
                echo -e "${YELLOW}⚠️  Auto-update failed. Please run manually: npm update -g claude-fsd${NC}"
                echo
            fi
        fi
    fi
}

# Check for updates (quick, non-blocking)
check_for_updates

# If no arguments provided, show interactive menu
if [ $# -eq 0 ]; then
    show_menu
    default_choice=$(get_default_choice)
    read -p "Enter your choice [$default_choice]: " choice
    choice=${choice:-$default_choice}  # Use smart default
    
    case $choice in
        0)
            # Create BRIEF.md in docs/ directory (preferred location)
            if ! find_brief_file >/dev/null 2>&1; then
                echo -e "${GREEN}Creating project brief...${NC}"
                echo
                mkdir -p docs
                echo "# Project Brief" > docs/BRIEF.md
                echo "" >> docs/BRIEF.md
                echo "## Vision" >> docs/BRIEF.md
                echo "Describe the big picture vision and what you want to achieve..." >> docs/BRIEF.md
                echo "" >> docs/BRIEF.md
                echo "## Core Requirements" >> docs/BRIEF.md
                echo "- Core requirement 1" >> docs/BRIEF.md
                echo "- Core requirement 2" >> docs/BRIEF.md
                echo "" >> docs/BRIEF.md
                echo "## Key Features" >> docs/BRIEF.md
                echo "- Feature 1" >> docs/BRIEF.md
                echo "- Feature 2" >> docs/BRIEF.md
                echo "" >> docs/BRIEF.md
                echo "## Success Criteria" >> docs/BRIEF.md
                echo "- Success criterion 1" >> docs/BRIEF.md
                echo "- Success criterion 2" >> docs/BRIEF.md
                
                open_with_editor "docs/BRIEF.md"
                echo
                echo -e "${GREEN}Brief created! Run claudefsd again to start the interview.${NC}"
            else
                echo -e "${RED}BRIEF.md already exists!${NC}"
                exit 1
            fi
            ;;
        1)
            # Interactive interview
            source "$(dirname "$0")/claudefsd-find-brief"
            brief_file=$(find_brief_file 2>/dev/null || echo "")
            if [ -z "$brief_file" ]; then
                echo -e "${RED}No BRIEF.md found. Please create a project brief first.${NC}"
                exit 1
            fi
            echo -e "${GREEN}Starting interview...${NC}"
            echo
            exec "$(dirname "$0")/claudefsd-interview"
            ;;
        2)
            # Create plan - check what source to use
            if [ -f docs/REQUIREMENTS.md ] || [ -f docs/QUESTIONS.md ]; then
                echo -e "${GREEN}Creating plan from project inputs...${NC}"
                echo
                exec "$(dirname "$0")/claudefsd-create-plan"
            else
                echo -e "${RED}No requirements or questions found. Please run the interview first.${NC}"
                exit 1
            fi
            ;;
        3)
            # Run development mode
            echo -e "${GREEN}Starting development mode...${NC}"
            echo
            exec "$(dirname "$0")/claudefsd-dev"
            ;;
        4)
            echo "Goodbye!"
            exit 0
            ;;
        *)
            echo -e "${RED}Invalid choice. Please run again.${NC}"
            exit 1
            ;;
    esac
else
    # If arguments provided, pass them through to the appropriate command
    case "$1" in
        interview)
            shift
            exec "$(dirname "$0")/claudefsd-interview" "$@"
            ;;
        dev|run)
            shift
            exec "$(dirname "$0")/claudefsd-dev" "$@"
            ;;
        create-plan)
            shift
            exec "$(dirname "$0")/claudefsd-create-plan" "$@"
            ;;
        *)
            echo -e "${RED}Unknown command: $1${NC}"
            echo
            echo "Usage: claudefsd [command]"
            echo
            echo "Commands:"
            echo "  interview      - Interactive requirements gathering"
            echo "  create-plan    - Create plan from requirements or questions"
            echo "  dev|run        - Run automated development mode"
            echo
            echo "Run without arguments for interactive mode."
            exit 1
            ;;
    esac
fi