#!/bin/bash

#############################################
# AI 夜間持續開發系統
# 每小時的 00, 20, 40 分自動執行
#############################################

set -e  # 遇到錯誤立即停止

# ============================================
# 配置區
# ============================================

# 嘗試載入環境配置檔案（優先順序：root > debian user）
ENV_FILES=(
    "/root/.ai-dev-env"
    "/home/debian/.ai-dev-env"
)

for env_file in "${ENV_FILES[@]}"; do
    if [ -f "$env_file" ]; then
        source "$env_file"
        echo "Loaded config from: $env_file"
        break
    fi
done

# 從環境變數讀取配置，或使用預設值
PROJECT_NAME="${AI_DEV_PROJECT:-sdd-management}"
PROJECT_DIR="${AI_DEV_PROJECT_DIR:-$HOME/projects/$PROJECT_NAME}"
AI_PROVIDER="${AI_DEV_AI_PROVIDER:-claude}"  # claude, copilot, gemini
ENABLE_LOOP="${AI_DEV_ENABLE:-true}"
LOG_DIR="${AI_DEV_LOG_DIR:-$HOME/.ai-dev-logs}"
MAX_ITERATIONS="${AI_DEV_MAX_ITERATIONS:-50}"  # 防止無限循環

# ============================================
# 初始化
# ============================================

# 創建必要的目錄
mkdir -p "$LOG_DIR"
mkdir -p "$PROJECT_DIR"

# Log 檔案路徑
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
SESSION_LOG="$LOG_DIR/${PROJECT_NAME}_${TIMESTAMP}.log"
MASTER_LOG="$LOG_DIR/master.log"
ITERATION_FILE="$PROJECT_DIR/.ai-dev-iteration"

# ============================================
# 日誌函數
# ============================================

log() {
    local level=$1
    shift
    local message="$@"
    local timestamp=$(date +"%Y-%m-%d %H:%M:%S")
    echo "[$timestamp] [$level] $message" | tee -a "$SESSION_LOG" >> "$MASTER_LOG"
}

log_info() {
    log "INFO" "$@"
}

log_error() {
    log "ERROR" "$@"
}

log_success() {
    log "SUCCESS" "$@"
}

# ============================================
# 檢查函數
# ============================================

check_if_should_continue() {
    # 檢查 ENV 變數是否允許繼續
    if [ "$ENABLE_LOOP" != "true" ]; then
        log_info "ENABLE_LOOP is not true, stopping execution"
        return 1
    fi
    
    # 檢查迭代次數
    local iteration=0
    if [ -f "$ITERATION_FILE" ]; then
        iteration=$(cat "$ITERATION_FILE")
    fi
    
    if [ "$iteration" -ge "$MAX_ITERATIONS" ]; then
        log_info "Reached max iterations ($MAX_ITERATIONS), stopping"
        return 1
    fi
    
    # 檢查專案完成標記
    if [ -f "$PROJECT_DIR/.project-completed" ]; then
        log_success "Project marked as completed"
        return 1
    fi
    
    return 0
}

increment_iteration() {
    local iteration=0
    if [ -f "$ITERATION_FILE" ]; then
        iteration=$(cat "$ITERATION_FILE")
    fi
    iteration=$((iteration + 1))
    echo "$iteration" > "$ITERATION_FILE"
    log_info "Iteration: $iteration"
}

# ============================================
# AI Provider 函數
# ============================================

get_prompt_file() {
    local prompt_file="$PROJECT_DIR/.ai-dev-prompt.txt"
    
    if [ ! -f "$prompt_file" ]; then
        log_error "Prompt file not found: $prompt_file"
        log_info "Creating template prompt file..."
        cat > "$prompt_file" <<'EOF'
# AI 開發 Prompt 模板
# 專案: ${PROJECT_NAME}

## 當前任務
請根據以下規格繼續開發專案：

[在這裡描述當前階段的開發任務]

## 輸出要求
1. 產生完整可執行的程式碼
2. 包含必要的註解
3. 遵循最佳實踐
4. 如果任務完成，請在最後一行輸出: TASK_COMPLETED

## 專案結構
[描述專案結構和已完成的部分]
EOF
        log_info "Template created at: $prompt_file"
        log_info "Please edit the prompt file and run again"
        exit 1
    fi
    
    echo "$prompt_file"
}

call_ai_provider() {
    local prompt_file=$1
    local prompt=$(cat "$prompt_file")
    local output_file="$PROJECT_DIR/.ai-dev-output-${TIMESTAMP}.txt"
    
    log_info "Calling AI provider: $AI_PROVIDER"
    
    case "$AI_PROVIDER" in
        claude)
            # 使用 Claude CLI
            if command -v claude &> /dev/null; then
                claude -p "$prompt" > "$output_file" 2>&1
            else
                log_error "Claude CLI not found. Install from: https://docs.anthropic.com/en/docs/claude-cli"
                return 1
            fi
            ;;
        copilot)
            # 使用 GitHub Copilot CLI
            if command -v copilot &> /dev/null; then
                copilot --allow-all-tools -p "$prompt" > "$output_file" 2>&1
            else
                log_error "GitHub Copilot CLI not found"
                return 1
            fi
            ;;
        gemini)
            # 使用 Gemini CLI (假設有這樣的工具)
            if command -v gemini &> /dev/null; then
                gemini --allowed-tools "write_file,run_shell_command" -p "$prompt" > "$output_file" 2>&1
            else
                log_error "Gemini CLI not found"
                return 1
            fi
            ;;
        *)
            log_error "Unknown AI provider: $AI_PROVIDER"
            return 1
            ;;
    esac
    
    local exit_code=$?
    if [ $exit_code -eq 0 ]; then
        log_success "AI execution completed"
        echo "$output_file"
        return 0
    else
        log_error "AI execution failed with exit code: $exit_code"
        return 1
    fi
}

# ============================================
# Git 函數
# ============================================

init_git_if_needed() {
    cd "$PROJECT_DIR"
    
    if [ ! -d ".git" ]; then
        log_info "Initializing git repository"
        git init
        git config user.name "AI Dev Bot"
        git config user.email "ai-dev@localhost"
    fi
}

git_commit_changes() {
    cd "$PROJECT_DIR"
    
    # 檢查是否有變更
    if git diff --quiet && git diff --cached --quiet; then
        log_info "No changes to commit"
        return 0
    fi
    
    # 添加所有變更（除了 .ai-dev-* 檔案）
    git add .
    git reset .ai-dev-* 2>/dev/null || true
    
    # 生成 commit message
    local commit_msg="AI Dev Session - $(date +"%Y-%m-%d %H:%M:%S")

Provider: $AI_PROVIDER
Iteration: $(cat "$ITERATION_FILE" 2>/dev/null || echo 0)
Session Log: $SESSION_LOG"
    
    git commit -m "$commit_msg"
    
    local commit_hash=$(git rev-parse --short HEAD)
    log_success "Changes committed: $commit_hash"
}

# ============================================
# 結果處理函數
# ============================================

process_ai_output() {
    local output_file=$1
    
    # 檢查是否包含完成標記
    if grep -q "TASK_COMPLETED" "$output_file"; then
        log_success "Task completed marker found"
        touch "$PROJECT_DIR/.project-completed"
        return 0
    fi
    
    # 這裡可以加入更多的結果處理邏輯
    # 例如：解析輸出、提取程式碼、更新檔案等
    
    log_info "Processing AI output..."
    # 可以在這裡添加自動應用程式碼的邏輯
    
    return 0
}

# ============================================
# 資料庫記錄函數
# ============================================

record_to_database() {
    local action=$1
    shift
    local params="$@"
    
    # 呼叫 Python 資料庫管理器
    SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
    python3 "$SCRIPT_DIR/db_manager.py" "$action" $params 2>/dev/null || true
}

# ============================================
# 主要執行流程
# ============================================

main() {
    log_info "========================================="
    log_info "AI Dev Loop Started"
    log_info "Project: $PROJECT_NAME"
    log_info "Directory: $PROJECT_DIR"
    log_info "AI Provider: $AI_PROVIDER"
    log_info "========================================="
    
    # 記錄開始時間
    local start_time=$(date +%s)
    
    # 檢查是否應該繼續執行
    if ! check_if_should_continue; then
        log_info "Execution stopped by check"
        exit 0
    fi
    
    # 增加迭代計數
    increment_iteration
    local current_iteration=$(cat "$ITERATION_FILE" 2>/dev/null || echo 0)
    
    # 初始化 Git
    init_git_if_needed
    
    # 獲取 prompt 檔案
    local prompt_file=$(get_prompt_file)
    local prompt_content=$(cat "$prompt_file")
    
    # 記錄執行開始到資料庫
    SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
    export PYTHONPATH="$SCRIPT_DIR:$PYTHONPATH"
    local execution_id=$(python3 -c "
import sys
sys.path.insert(0, '$SCRIPT_DIR')
from db_manager import record_execution_start
eid = record_execution_start('$PROJECT_NAME', '''$prompt_content''', '$AI_PROVIDER', $current_iteration)
print(eid)
" 2>/dev/null)
    
    log_info "Database execution ID: $execution_id"
    
    # 呼叫 AI
    local output_file
    local exit_code=0
    if output_file=$(call_ai_provider "$prompt_file"); then
        # 處理輸出
        process_ai_output "$output_file"
        
        # Git commit
        git_commit_changes
        
        # 獲取 commit hash
        cd "$PROJECT_DIR"
        local commit_hash=$(git rev-parse --short HEAD 2>/dev/null || echo "")
        
        # 計算執行時間
        local end_time=$(date +%s)
        local duration=$((end_time - start_time))
        
        # 讀取 AI 輸出
        local ai_output=$(cat "$output_file" 2>/dev/null || echo "")
        
        # 估算 token 數（粗略估計：字數 * 1.3）
        local token_estimate=$(echo "$ai_output" | wc -w | awk '{print int($1 * 1.3)}')
        
        # 記錄執行完成到資料庫
        python3 -c "
import sys
sys.path.insert(0, '$SCRIPT_DIR')
from db_manager import record_execution_complete
record_execution_complete(
    $execution_id,
    '''$ai_output''',
    '$commit_hash',
    $duration,
    'completed',
    None,
    $token_estimate
)
" 2>/dev/null || true
        
        log_success "Session completed successfully"
    else
        exit_code=1
        
        # 計算執行時間
        local end_time=$(date +%s)
        local duration=$((end_time - start_time))
        
        # 記錄執行失敗到資料庫
        python3 -c "
import sys
sys.path.insert(0, '$SCRIPT_DIR')
from db_manager import record_execution_complete
record_execution_complete(
    $execution_id,
    '',
    '',
    $duration,
    'failed',
    'AI execution failed',
    0
)
" 2>/dev/null || true
        
        log_error "Session failed"
    fi
    
    log_info "========================================="
    log_info "Next execution at: $(date -d '+20 minutes' '+%Y-%m-%d %H:%M')"
    log_info "========================================="
    
    exit $exit_code
}

# 執行主程式
main "$@"
