"""
Cleanup script for timesheet project
Removes debug, test, and temporary files
"""

import os
import shutil
from pathlib import Path

# Base directory
BASE_DIR = Path("E:/timesheet/timesheet_new")
TRASH_DIR = BASE_DIR / "__cleanup_trash__"

# Create trash directory if it doesn't exist
TRASH_DIR.mkdir(exist_ok=True)

# Files to keep (important files)
KEEP_FILES = {
    "main.py", "models.py", "schemas.py", "database.py", "config.py", 
    "auth.py", "crud.py", "requirements.txt", ".gitignore",
    "activity_categorizer.py", "activity_categorization_api.py",
    "activitywatch_sync.py", "activitywatch_webhook.py",
    "dashboard_api.py", "productivity_api.py", "all_developers_simple.py",
    ".env", ".env.example", ".env.local", ".env.production",
    "package.json", "package-lock.json"
}

# Patterns for files to remove
REMOVE_PATTERNS = {
    # Root directory patterns
    "root": [
        "CHECK-*.bat", "DEBUG-*.bat", "DIAGNOSE-*.bat", "FIX-*.bat",
        "TEST-*.bat", "QUICK-*.bat", "ONE-*.bat", "RUN-*.bat", 
        "VERIFY-*.bat", "START-*.bat", "COMPLETE-*.bat",
        "check_*.py", "test_*.py", "fix_*.py", "quick_*.py", 
        "simple_*.py", "temporary_*.py", "verify_*.py", "find_*.py",
        "fix_*.sql", "test_*.sql", "simple_*.sql", "emergency_*.sql", 
        "diagnostic_*.sql", "mysql_*.sql", "postgresql_*.sql",
        "*_README.md", "*_GUIDE.md", "*_PLAN.md", "*_NOW.md",
        "*.txt", "*.sh", "*.vbs", "*.ps1",
        "working_*.py", "update_*.py", "frontend_*.js"
    ],
    # Backend directory patterns
    "backend": [
        "debug_*.py", "test_*.py", "diagnose_*.py", "check_*.py",
        "fix_*.py", "quick_*.py", "simple_*.py", "minimal_*.py",
        "*.backup", "*_old.py", "*_fixed.py", "*_enhanced.py",
        "*.html", "*.bat", "*.sh",
        "sample_*.py", "setup_*.py", "migrate_*.py",
        "force_*.py", "flexible_*.py", "extract_*.py",
        "find_*.py", "add_*.py", "remove_*.py",
        "inspect_*.py", "query_*.py", "realistic_*.py",
        "open_*.py", "categorize_*.py", "improved_*.py",
        "dynamic_*.py", "start_*.py", "New Text Document.txt"
    ],
    # Frontend directory patterns
    "frontend": [
        "fix-*.ps1"
    ]
}

def should_remove_file(filepath, patterns, keep_files):
    """Check if file should be removed based on patterns"""
    filename = filepath.name
    
    # Always keep important files
    if filename in keep_files:
        return False
    
    # Check against remove patterns
    for pattern in patterns:
        if "*" in pattern:
            # Handle wildcard patterns
            prefix = pattern.split("*")[0]
            suffix = pattern.split("*")[1] if len(pattern.split("*")) > 1 else ""
            
            if prefix and suffix:
                if filename.startswith(prefix) and filename.endswith(suffix):
                    return True
            elif prefix:
                if filename.startswith(prefix):
                    return True
            elif suffix:
                if filename.endswith(suffix):
                    return True
        else:
            # Exact match
            if filename == pattern:
                return True
    
    return False

def cleanup_directory(directory, patterns, keep_files, trash_subdir):
    """Clean up a directory by moving files to trash"""
    removed_count = 0
    kept_count = 0
    
    # Create subdirectory in trash
    trash_path = TRASH_DIR / trash_subdir
    trash_path.mkdir(exist_ok=True)
    
    for item in directory.iterdir():
        if item.is_file():
            if should_remove_file(item, patterns, keep_files):
                try:
                    # Move to trash
                    dest = trash_path / item.name
                    # Handle duplicate names
                    counter = 1
                    while dest.exists():
                        stem = item.stem
                        suffix = item.suffix
                        dest = trash_path / f"{stem}_{counter}{suffix}"
                        counter += 1
                    
                    shutil.move(str(item), str(dest))
                    print(f"  Moved: {item.name}")
                    removed_count += 1
                except Exception as e:
                    print(f"  Error moving {item.name}: {e}")
            else:
                kept_count += 1
    
    return removed_count, kept_count

def main():
    """Main cleanup function"""
    print("=" * 60)
    print("TIMESHEET PROJECT CLEANUP")
    print("=" * 60)
    
    total_removed = 0
    total_kept = 0
    
    # Clean root directory
    print("\n1. Cleaning ROOT directory...")
    removed, kept = cleanup_directory(
        BASE_DIR, 
        REMOVE_PATTERNS["root"], 
        KEEP_FILES,
        "root"
    )
    total_removed += removed
    total_kept += kept
    print(f"   Removed: {removed} files, Kept: {kept} files")
    
    # Clean backend directory
    backend_dir = BASE_DIR / "backend"
    if backend_dir.exists():
        print("\n2. Cleaning BACKEND directory...")
        removed, kept = cleanup_directory(
            backend_dir, 
            REMOVE_PATTERNS["backend"], 
            KEEP_FILES,
            "backend"
        )
        total_removed += removed
        total_kept += kept
        print(f"   Removed: {removed} files, Kept: {kept} files")
    
    # Clean frontend directory
    frontend_dir = BASE_DIR / "frontend"
    if frontend_dir.exists():
        print("\n3. Cleaning FRONTEND directory...")
        removed, kept = cleanup_directory(
            frontend_dir, 
            REMOVE_PATTERNS["frontend"], 
            KEEP_FILES,
            "frontend"
        )
        total_removed += removed
        total_kept += kept
        print(f"   Removed: {removed} files, Kept: {kept} files")
    
    # Remove empty debug directories
    print("\n4. Removing empty debug directories...")
    debug_dirs = ["debug", "logs", "__pycache__", "__to_delete__"]
    for dirname in debug_dirs:
        # Check in root
        dirpath = BASE_DIR / dirname
        if dirpath.exists() and dirpath.is_dir():
            try:
                shutil.move(str(dirpath), str(TRASH_DIR / f"dir_{dirname}"))
                print(f"   Moved directory: {dirname}")
            except Exception as e:
                print(f"   Error moving {dirname}: {e}")
        
        # Check in backend
        backend_dirpath = backend_dir / dirname
        if backend_dirpath.exists() and backend_dirpath.is_dir():
            try:
                shutil.move(str(backend_dirpath), str(TRASH_DIR / f"backend_dir_{dirname}"))
                print(f"   Moved backend directory: {dirname}")
            except Exception as e:
                print(f"   Error moving backend/{dirname}: {e}")
    
    print("\n" + "=" * 60)
    print(f"CLEANUP COMPLETE!")
    print(f"Total files moved to trash: {total_removed}")
    print(f"Total files kept: {total_kept}")
    print(f"\nAll removed files are in: {TRASH_DIR}")
    print("Review the trash directory and delete permanently when ready.")
    print("=" * 60)

if __name__ == "__main__":
    main()
