#!/bin/bash

# 檔案組織工具
# 用於快速歸類無法明確分類的檔案

show_help() {
    echo "📁 檔案組織工具"
    echo "==============="
    echo ""
    echo "用法: $0 [檔案名] [類型]"
    echo ""
    echo "類型選項:"
    echo "  temp     - 臨時檔案 (放入 temp/)"
    echo "  archive  - 歷史檔案 (放入 archive/今日日期/)"
    echo "  misc     - 雜項檔案 (放入 misc/)"
    echo "  auto     - 自動決定位置"
    echo ""
    echo "範例:"
    echo "  $0 test_script.sh temp"
    echo "  $0 old_config.json archive"
    echo "  $0 unknown_file.txt auto"
}

# 自動決策函數
auto_categorize() {
    local file="$1"
    local filename=$(basename "$file")
    
    # 檢查檔案名模式
    if [[ "$filename" =~ ^(test_|temp_|tmp_|debug_) ]]; then
        echo "temp"
    elif [[ "$filename" =~ ^(old_|backup_|archive_) ]]; then
        echo "archive"
    elif [[ "$filename" =~ \.(log|tmp|bak)$ ]]; then
        echo "temp"
    else
        echo "misc"
    fi
}

# 移動檔案函數
move_file() {
    local file="$1"
    local category="$2"
    local dest_dir
    
    case "$category" in
        "temp")
            dest_dir="temp"
            ;;
        "archive")
            dest_dir="archive/$(date +%Y-%m-%d)"
            ;;
        "misc")
            dest_dir="misc"
            ;;
        *)
            echo "❌ 未知的分類: $category"
            return 1
            ;;
    esac
    
    # 創建目標目錄
    mkdir -p "$dest_dir"
    
    # 移動檔案
    if mv "$file" "$dest_dir/"; then
        echo "✅ 已移動 '$file' → '$dest_dir/'"
        
        # 記錄移動
        echo "$(date '+%Y-%m-%d %H:%M:%S') - Moved '$file' to '$dest_dir/' (category: $category)" >> "$dest_dir/.move_log"
    else
        echo "❌ 移動失敗: '$file'"
        return 1
    fi
}

# 主程序
main() {
    if [ $# -eq 0 ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
        show_help
        exit 0
    fi
    
    local file="$1"
    local category="$2"
    
    # 檢查檔案是否存在
    if [ ! -f "$file" ]; then
        echo "❌ 檔案不存在: $file"
        exit 1
    fi
    
    # 如果沒有指定分類或指定為 auto，則自動決定
    if [ -z "$category" ] || [ "$category" = "auto" ]; then
        category=$(auto_categorize "$file")
        echo "🤖 自動分類為: $category"
    fi
    
    # 確認移動
    echo "準備移動檔案:"
    echo "  檔案: $file"
    echo "  分類: $category"
    echo ""
    read -p "確認移動？ (y/N): " confirm
    
    if [[ "$confirm" =~ ^[Yy]$ ]]; then
        move_file "$file" "$category"
    else
        echo "已取消"
    fi
}

# 執行主程序
main "$@"