#!/bin/bash

# Momentry Storage 管理 (Layer 7)
# 路徑: /Users/accusys/momentry_core_0.1/monitor/storage/storage_manager.sh

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LOG_DIR="/Users/accusys/momentry/log/monitor"

mkdir -p "$LOG_DIR"
LOG_FILE="$LOG_DIR/storage_check.log"

log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

# 存儲路徑配置
STORAGE_BASE="/Users/accusys/momentry"
DATA_DIR="$STORAGE_BASE/data"
TEMP_DIR="$STORAGE_BASE/tmp"
BACKUP_DIR="$STORAGE_BASE/backup"

# 用戶集群
CLUSTERS=("family" "work" "wordpress" "shared")

# 記錄使用統計
record_usage() {
    local cluster=$1
    local tier=$2
    local file_count=$3
    local total_size=$4
    
    psql -U accusys -h localhost -d momentry << EOF 2>/dev/null
INSERT INTO storage_usage_stats (user_cluster, storage_tier, file_count, total_size_bytes, record_time)
VALUES ('$cluster', '$tier', $file_count, $total_size, NOW());
EOF
}

# 記錄檔案註冊
register_file() {
    local file_path=$1
    local user_cluster=$2
    local file_size=$3
    
    file_name=$(basename "$file_path")
    file_hash=$(echo "$file_path" | md5sum | cut -d' ' -f1)
    
    psql -U accusys -h localhost -d momentry << EOF 2>/dev/null
INSERT INTO file_registry (file_name, file_path, file_path_hash, file_size, user_cluster, storage_tier, status, created_at)
VALUES ('$file_name', '$file_path', '$file_hash', $file_size, '$user_cluster', 'hot', 'active', NOW())
ON CONFLICT (file_path_hash) DO UPDATE SET
    last_accessed_at = NOW(),
    access_count = file_registry.access_count + 1;
EOF
}

# 初始化目錄結構
init_directories() {
    echo "初始化目錄結構..."
    
    # 主目錄
    mkdir -p "$DATA_DIR"
    mkdir -p "$TEMP_DIR"
    mkdir -p "$BACKUP_DIR"/{daily,weekly,monthly,archive}
    
    # 用戶集群目錄
    for cluster in "${CLUSTERS[@]}"; do
        mkdir -p "$DATA_DIR/$cluster"
    done
    
    # 臨時子目錄
    mkdir -p "$TEMP_DIR"/{upload,processing,cache,session}
    
    echo "目錄結構已初始化"
}

# 顯示存儲狀態
show_status() {
    echo "========================================"
    echo "Layer 7: Storage Status"
    echo "Time: $(date)"
    echo "========================================"
    echo ""
    
    echo "存儲路徑:"
    echo "  數據: $DATA_DIR"
    echo "  臨時: $TEMP_DIR"
    echo "  備份: $BACKUP_DIR"
    echo ""
    
    echo "用戶集群:"
    echo "----------------------------------------"
    
    for cluster in "${CLUSTERS[@]}"; do
        cluster_path="$DATA_DIR/$cluster"
        if [ -d "$cluster_path" ]; then
            file_count=$(find "$cluster_path" -type f 2>/dev/null | wc -l)
            total_size=$(du -sb "$cluster_path" 2>/dev/null | cut -f1)
            
            size_str="0B"
            if [ -n "$total_size" ] && [ "$total_size" -gt 0 ] 2>/dev/null; then
                if [ "$total_size" -gt 1073741824 ]; then
                    size_str="$((total_size / 1073741824))GB"
                elif [ "$total_size" -gt 1048576 ]; then
                    size_str="$((total_size / 1048576))MB"
                elif [ "$total_size" -gt 1024 ]; then
                    size_str="$((total_size / 1024))KB"
                else
                    size_str="${total_size}B"
                fi
            fi
            
            echo "  $cluster: $file_count files, $size_str"
            [ -n "$total_size" ] && record_usage "$cluster" "hot" "$file_count" "$total_size"
        else
            echo "  $cluster: (未創建)"
        fi
    done
    
    echo ""
    echo "臨時文件:"
    echo "----------------------------------------"
    
    for subdir in upload processing cache session; do
        subdir_path="$TEMP_DIR/$subdir"
        if [ -d "$subdir_path" ]; then
            file_count=$(find "$subdir_path" -type f 2>/dev/null | wc -l)
            size=$(du -sb "$subdir_path" 2>/dev/null | cut -f1)
            echo "  $subdir: $file_count files"
        fi
    done
    
    echo ""
    echo "備份目錄:"
    echo "----------------------------------------"
    
    for subdir in daily weekly monthly archive; do
        subdir_path="$BACKUP_DIR/$subdir"
        if [ -d "$subdir_path" ]; then
            file_count=$(find "$subdir_path" -type f 2>/dev/null | wc -l)
            size=$(du -sb "$subdir_path" 2>/dev/null | cut -f1)
            echo "  $subdir: $file_count files"
        fi
    done
    
    echo ""
    echo "========================================"
    
    # 顯示資料庫統計
    echo ""
    echo "資料庫統計 (file_registry):"
    psql -U accusys -h localhost -d momentry -t -A -c "
        SELECT user_cluster, storage_tier, COUNT(*) as files, 
               SUM(file_size)::bigint as total_size
        FROM file_registry 
        WHERE status = 'active'
        GROUP BY user_cluster, storage_tier;
    " 2>/dev/null || echo "  (表未初始化)"
}

# 清理臨時文件
clean_temp() {
    echo "清理臨時文件..."
    
    # 清理超過 7 天的上傳
    find "$TEMP_DIR/upload" -type f -mtime +7 -delete 2>/dev/null
    
    # 清理超過 30 天的緩存
    find "$TEMP_DIR/cache" -type f -mtime +30 -delete 2>/dev/null
    
    # 清理超過 7 天的處理中
    find "$TEMP_DIR/processing" -type f -mtime +7 -delete 2>/dev/null
    
    echo "清理完成"
}

# 主程序
command=${1:-status}

case $command in
    status)
        show_status
        ;;
    init)
        init_directories
        ;;
    clean)
        clean_temp
        ;;
    *)
        echo "用法: $0 {status|init|clean}"
        exit 1
        ;;
esac
