#!/bin/bash

# Drama Ling 專案例行作業管理器
# 用途：統一管理和執行各種例行檢查和維護作業
# 作者：Claude Code Assistant
# 版本：1.0

# 設定
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
REPORTS_DIR="$SCRIPT_DIR/reports"
LOGS_DIR="$SCRIPT_DIR/logs"
CONFIG_DIR="$SCRIPT_DIR/config"

# 確保目錄存在
mkdir -p "$REPORTS_DIR" "$LOGS_DIR"

# 顏色定義
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# 時間戳
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
DATE_SIMPLE=$(date +"%Y-%m-%d")

# 顯示標題
show_header() {
    echo -e "${CYAN}=================================================${NC}"
    echo -e "${CYAN}    Drama Ling 專案例行作業管理器${NC}"
    echo -e "${CYAN}    執行時間: $(date)${NC}"
    echo -e "${CYAN}=================================================${NC}"
    echo ""
}

# 顯示使用說明
show_help() {
    echo -e "${BLUE}使用方法:${NC}"
    echo "  $0 [選項]"
    echo ""
    echo -e "${BLUE}選項:${NC}"
    echo "  all                執行所有例行作業"
    echo "  consistency        執行文檔一致性檢查"
    echo "  quality           執行文檔品質檢查"
    echo "  security          執行安全性檢查"
    echo "  dependencies      執行相依性檢查"
    echo "  structure         執行專案結構檢查"
    echo "  issues            檢查問題追蹤狀態"
    echo "  report            生成綜合報告"
    echo "  schedule          設置定期執行排程"
    echo "  history           查看執行歷史"
    echo "  clean             清理舊的報告和日誌"
    echo "  help              顯示此幫助訊息"
    echo ""
    echo -e "${BLUE}範例:${NC}"
    echo "  $0 all                    # 執行所有檢查"
    echo "  $0 consistency quality    # 只執行指定的檢查"
    echo "  $0 report                # 只生成報告"
}

# 記錄日誌
log_message() {
    local level=$1
    local message=$2
    echo "[$(date +'%Y-%m-%d %H:%M:%S')] [$level] $message" >> "$LOGS_DIR/maintenance_${DATE_SIMPLE}.log"
}

# 執行檢查並記錄結果
run_check() {
    local check_name=$1
    local script_path=$2
    local description=$3
    
    echo -e "${YELLOW}📋 執行: $description${NC}"
    log_message "INFO" "開始執行: $check_name"
    
    if [ -f "$script_path" ]; then
        # 執行檢查並捕獲輸出
        local output_file="$REPORTS_DIR/${check_name}_${TIMESTAMP}.txt"
        local start_time=$(date +%s)
        
        if bash "$script_path" > "$output_file" 2>&1; then
            local end_time=$(date +%s)
            local duration=$((end_time - start_time))
            echo -e "${GREEN}✅ 完成: $description (耗時: ${duration}s)${NC}"
            log_message "SUCCESS" "$check_name 執行成功，耗時: ${duration}s"
            return 0
        else
            echo -e "${RED}❌ 失敗: $description${NC}"
            log_message "ERROR" "$check_name 執行失敗"
            return 1
        fi
    else
        echo -e "${RED}❌ 腳本不存在: $script_path${NC}"
        log_message "ERROR" "腳本不存在: $script_path"
        return 1
    fi
}

# 執行文檔一致性檢查
check_consistency() {
    echo -e "${PURPLE}🔍 === 文檔一致性檢查 ===${NC}"
    run_check "consistency" "$SCRIPT_DIR/maintenance/check_consistency.sh" "文檔一致性檢查"
}

# 執行文檔品質檢查
check_quality() {
    echo -e "${PURPLE}📚 === 文檔品質檢查 ===${NC}"
    run_check "quality" "$SCRIPT_DIR/maintenance/check_doc_quality.sh" "文檔品質檢查"
}

# 執行安全性檢查
check_security() {
    echo -e "${PURPLE}🔒 === 安全性檢查 ===${NC}"
    run_check "security" "$SCRIPT_DIR/maintenance/check_security.sh" "安全性檢查"
}

# 執行相依性檢查
check_dependencies() {
    echo -e "${PURPLE}📦 === 相依性檢查 ===${NC}"
    run_check "dependencies" "$SCRIPT_DIR/maintenance/check_dependencies.sh" "相依性檢查"
}

# 執行專案結構檢查
check_structure() {
    echo -e "${PURPLE}🏗️ === 專案結構檢查 ===${NC}"
    run_check "structure" "$SCRIPT_DIR/maintenance/check_project_structure.sh" "專案結構檢查"
}

# 執行問題追蹤檢查
check_issues() {
    echo -e "${PURPLE}🔍 === 問題追蹤檢查 ===${NC}"
    run_check "issues" "$SCRIPT_DIR/maintenance/check_issues.sh" "問題追蹤檢查"
}

# 生成綜合報告
generate_report() {
    echo -e "${PURPLE}📊 === 生成綜合報告 ===${NC}"
    local report_file="$REPORTS_DIR/comprehensive_report_${TIMESTAMP}.html"
    
    # 這裡會呼叫報告生成腳本
    if [ -f "$SCRIPT_DIR/maintenance/generate_report.sh" ]; then
        bash "$SCRIPT_DIR/maintenance/generate_report.sh" "$REPORTS_DIR" "$report_file"
        echo -e "${GREEN}✅ 綜合報告已生成: $report_file${NC}"
    else
        echo -e "${YELLOW}⚠️ 報告生成腳本不存在，跳過${NC}"
    fi
}

# 設置定期執行排程
setup_schedule() {
    echo -e "${PURPLE}⏰ === 設置定期執行排程 ===${NC}"
    echo "選擇排程頻率："
    echo "1) 每日執行 (09:00)"
    echo "2) 每週執行 (週一 09:00)"
    echo "3) 每月執行 (1號 09:00)"
    echo "4) 自定義"
    echo "5) 移除現有排程"
    
    read -p "請選擇 (1-5): " choice
    
    case $choice in
        1)
            (crontab -l 2>/dev/null; echo "0 9 * * * cd $PROJECT_ROOT && $SCRIPT_DIR/maintenance_manager.sh all") | crontab -
            echo -e "${GREEN}✅ 已設置每日執行排程${NC}"
            ;;
        2)
            (crontab -l 2>/dev/null; echo "0 9 * * 1 cd $PROJECT_ROOT && $SCRIPT_DIR/maintenance_manager.sh all") | crontab -
            echo -e "${GREEN}✅ 已設置每週執行排程${NC}"
            ;;
        3)
            (crontab -l 2>/dev/null; echo "0 9 1 * * cd $PROJECT_ROOT && $SCRIPT_DIR/maintenance_manager.sh all") | crontab -
            echo -e "${GREEN}✅ 已設置每月執行排程${NC}"
            ;;
        4)
            echo "請參考 crontab 格式設置自定義排程"
            echo "範例: 0 9 * * 1-5 表示工作日上午9點執行"
            ;;
        5)
            crontab -l 2>/dev/null | grep -v "maintenance_manager.sh" | crontab -
            echo -e "${GREEN}✅ 已移除相關排程${NC}"
            ;;
        *)
            echo -e "${RED}❌ 無效選擇${NC}"
            ;;
    esac
}

# 查看執行歷史
show_history() {
    echo -e "${PURPLE}📜 === 執行歷史 ===${NC}"
    if [ -d "$LOGS_DIR" ] && [ "$(ls -A $LOGS_DIR)" ]; then
        echo "最近的日誌檔案："
        ls -lt "$LOGS_DIR"/*.log 2>/dev/null | head -5
        echo ""
        echo "最新的執行記錄："
        tail -20 "$LOGS_DIR"/maintenance_*.log 2>/dev/null || echo "無執行記錄"
    else
        echo "無執行歷史記錄"
    fi
    
    echo ""
    echo "最近的報告："
    if [ -d "$REPORTS_DIR" ] && [ "$(ls -A $REPORTS_DIR)" ]; then
        ls -lt "$REPORTS_DIR"/* 2>/dev/null | head -5
    else
        echo "無報告記錄"
    fi
}

# 清理舊檔案
clean_old_files() {
    echo -e "${PURPLE}🧹 === 清理舊檔案 ===${NC}"
    read -p "刪除幾天前的檔案？ (預設: 30): " days
    days=${days:-30}
    
    if [ "$days" -gt 0 ]; then
        echo "刪除 $days 天前的日誌和報告..."
        find "$LOGS_DIR" -name "*.log" -mtime +$days -delete 2>/dev/null
        find "$REPORTS_DIR" -name "*" -mtime +$days -delete 2>/dev/null
        echo -e "${GREEN}✅ 清理完成${NC}"
    else
        echo -e "${RED}❌ 無效的天數${NC}"
    fi
}

# 主要邏輯
main() {
    show_header
    
    if [ $# -eq 0 ]; then
        show_help
        exit 1
    fi
    
    # 記錄開始執行
    log_message "START" "開始執行例行作業: $*"
    
    local total_checks=0
    local successful_checks=0
    
    # 處理參數
    while [ $# -gt 0 ]; do
        case $1 in
            all)
                total_checks=$((total_checks + 6))
                check_consistency && successful_checks=$((successful_checks + 1))
                check_quality && successful_checks=$((successful_checks + 1))
                check_security && successful_checks=$((successful_checks + 1))
                check_dependencies && successful_checks=$((successful_checks + 1))
                check_structure && successful_checks=$((successful_checks + 1))
                check_issues && successful_checks=$((successful_checks + 1))
                generate_report
                ;;
            consistency)
                total_checks=$((total_checks + 1))
                check_consistency && successful_checks=$((successful_checks + 1))
                ;;
            quality)
                total_checks=$((total_checks + 1))
                check_quality && successful_checks=$((successful_checks + 1))
                ;;
            security)
                total_checks=$((total_checks + 1))
                check_security && successful_checks=$((successful_checks + 1))
                ;;
            dependencies)
                total_checks=$((total_checks + 1))
                check_dependencies && successful_checks=$((successful_checks + 1))
                ;;
            structure)
                total_checks=$((total_checks + 1))
                check_structure && successful_checks=$((successful_checks + 1))
                ;;
            issues)
                total_checks=$((total_checks + 1))
                check_issues && successful_checks=$((successful_checks + 1))
                ;;
            report)
                generate_report
                ;;
            schedule)
                setup_schedule
                ;;
            history)
                show_history
                ;;
            clean)
                clean_old_files
                ;;
            help)
                show_help
                ;;
            *)
                echo -e "${RED}❌ 未知選項: $1${NC}"
                show_help
                exit 1
                ;;
        esac
        shift
    done
    
    # 顯示執行總結
    if [ $total_checks -gt 0 ]; then
        echo ""
        echo -e "${CYAN}=================================================${NC}"
        echo -e "${CYAN}執行總結:${NC}"
        echo -e "總檢查項目: $total_checks"
        echo -e "成功執行: ${GREEN}$successful_checks${NC}"
        echo -e "失敗項目: ${RED}$((total_checks - successful_checks))${NC}"
        
        if [ $successful_checks -eq $total_checks ]; then
            echo -e "${GREEN}🎉 所有檢查都執行成功！${NC}"
            log_message "SUCCESS" "所有例行作業執行成功"
        else
            echo -e "${YELLOW}⚠️ 部分檢查執行失敗，請查看詳細報告${NC}"
            log_message "WARNING" "部分例行作業執行失敗"
        fi
        echo -e "${CYAN}=================================================${NC}"
    fi
}

# 執行主程式
main "$@"