"""
Cleanup script for timesheet project - Simplified version
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", "README-SETUP.txt"
}

def cleanup_root():
    """Clean root directory files"""
    print("\n1. Cleaning ROOT directory...")
    moved = 0
    
    # Create root trash subdirectory
    root_trash = TRASH_DIR / "root"
    root_trash.mkdir(exist_ok=True)
    
    # List of files to remove from root
    files_to_remove = [
        # BAT files
        "CHECK-AUTOMATION-STATUS.bat", "CHECK-STATUS.bat", "CLICK-TO-FIX-MAIL.bat",
        "COMPLETE-AUTOMATION-SOLUTION.bat", "COMPLETE-FIX-FIRST-ECONOMY-MAIL.bat",
        "CONFIGURE-FIRST.bat", "CREATE-DEVELOPER-PACKAGE.bat", "DEBUG-SYNC.bat",
        "DEBUG-VERBOSE-SYNC.bat", "DIAGNOSE-HANGING-SYNC.bat", "FINAL-FIX-RUN-THIS.bat",
        "FIX-AND-START-NOW.bat", "FIX-CATEGORIES-NO-ERRORS.bat", "FIX-MAIL-IN-PRODUCTIVE.bat",
        "FIX-NONPRODUCTIVE-IN-PRODUCTIVE.bat", "FIX-POSTGRES-AUTH.bat", "FIX-SERVER-ERROR.bat",
        "FIX-SYNC-NOW.bat", "INSTALL-UBUNTU-AUTOSTART.bat", "ONE-CLICK-INSTALL.bat",
        "ONE-TIME-SETUP.bat", "QUICK-FIX-GMAIL-YOUTUBE.bat", "QUICK-TEST.bat",
        "RUN-PYTHON-FIX.bat", "RUN-SYNC-MANUAL.bat", "RUN-THIS-TO-FIX-MAIL.bat",
        "START-HERE.bat", "start_sync.bat", "SYNC-MANAGER.bat", "TEST-RESTART-SIMULATION.bat",
        "TEST-SERVER.bat", "ULTIMATE-ONE-CLICK.bat", "VERIFY-AUTOSTART.bat",
        "WHICH-DEVELOPER.bat", "YES-AUTOSTART-WORKS.bat",
        
        # Python test/debug files
        "check_productive_category.py", "find_error_line.py", "fix_activity_categories.py",
        "fix_all_mail_activities.py", "fix_categories_no_auth_issues.py", "fix_with_any_db_config.py",
        "frontend_project_grouping_example.js", "ONE_CLICK_MAIL_FIX.py", "quick_fix_commands.sh",
        "quick_fix_first_economy_mail.py", "quick_fix_project_grouping.py", "simple_api_fix.py",
        "simple_python_fix.py", "temporary_diagnostic_endpoint.py", "test_categorizer_fix.py",
        "test_startup_error.py", "update_all_categories.py", "verify_categories.py",
        "working_main_function.py",
        
        # SQL files
        "COPY_PASTE_THIS.sql", "diagnostic_queries.sql", "emergency_mail_fix.sql",
        "fix_nonproductive_quick.sql", "fix_nonproductive_quick_fixed.sql",
        "fix_project_extraction.sql", "fix_your_data_now.sql", "mysql_fix.sql",
        "postgresql_fix.sql", "POSTGRESQL_FIX_RUN_THIS.sql", "postgresql_update_projects.sql",
        "simple_fix.sql", "simple_postgres_fix.sql", "test_fix.sql", "test_postgresql_fix.sql",
        "test_project_grouping.sql", "update_project_names.sql",
        
        # MD/TXT files (except README-SETUP.txt)
        "ALL-SCRIPTS-LIST.txt", "ALL-SOLUTIONS-SUMMARY.txt", "COMPLETE_MAIL_FIX_SOLUTION.md",
        "DO-THIS-FIRST.txt", "DO_THIS_NOW.md", "EMERGENCY_FIX.md", "FILES-CREATED.txt",
        "FINAL-COMPLETE-GUIDE.txt", "find_and_fix_commands.md", "FIX_FIRST_ECONOMY_MAIL_README.md",
        "FIX_GMAIL_YOUTUBE_README.md", "fix_import_error.md", "FIX_POSTGRESQL_NOW.md",
        "FIX_ROUND_ERROR_README.md", "FIX_STARTUP_ERROR_NOW.md", "postgresql_vs_mysql.md",
        "projects_endpoint_fix.md", "PROJECT_GROUPING_FIX_COMPLETE.md", "PROJECT_GROUPING_GUIDE.md",
        "POSTGRESQL_RUN_NOW.md", "QUICK_ACTION_PLAN.txt", "SIMPLE_ACTION_PLAN.md",
        "TROUBLESHOOTING-GUIDE.txt", "WEB-FORM-TEMPLATE.txt", "WHERE_TO_LOOK.md",
        "which_database.md", "WINDOWS-TO-UBUNTU-SYNC-EXPLAINED.txt",
        
        # Script files
        "fix_categories.sh", "sync.ps1", "sync.sh", "hidden-launcher.vbs"
    ]
    
    for filename in files_to_remove:
        filepath = BASE_DIR / filename
        if filepath.exists() and filepath.is_file():
            try:
                dest = root_trash / filename
                shutil.move(str(filepath), str(dest))
                print(f"  Moved: {filename}")
                moved += 1
            except Exception as e:
                print(f"  Error moving {filename}: {e}")
    
    return moved

def cleanup_backend():
    """Clean backend directory files"""
    print("\n2. Cleaning BACKEND directory...")
    moved = 0
    
    backend_dir = BASE_DIR / "backend"
    if not backend_dir.exists():
        return 0
    
    # Create backend trash subdirectory
    backend_trash = TRASH_DIR / "backend"
    backend_trash.mkdir(exist_ok=True)
    
    # List of files to remove from backend
    files_to_remove = [
        # Debug files
        "debug_activitywatch_time.py", "debug_activity_endpoint.py", "debug_activity_records.py",
        "debug_activity_sqlalchemy.py", "debug_api_error.py", "debug_duration_issue.py",
        "debug_duration_issue_fixed.py", "debug_table.py", "debug_total_time.py",
        "debug_uvicorn_import.py", "debug_window_titles.py", "debug_working_hours.py",
        
        # Test files
        "test_activity_api.py", "test_activity_categories_endpoint.py", "test_api_endpoints.py",
        "test_categorizer.py", "test_column_types.py", "test_dashboard_data.py",
        "test_db_connection.py", "test_developers_endpoint.py", "test_new_categorization.py",
        "test_orm_issue.py", "test_relationships.py", "test_sync_endpoint.py",
        
        # Check/diagnose files
        "check_activity_data.py", "check_activity_json.py", "check_api_logs.py",
        "check_data_types.py", "check_date_issue.py", "check_date_issue_fixed.py",
        "check_db_types.py", "check_developers_table.py", "check_developer_alignment.py",
        "check_developer_data.py", "diagnose_500_error.bat", "diagnose_dashboard.bat",
        "diagnose_linux_server.py", "diagnose_startup.py",
        
        # Fix files
        "fix_activity_api_500.py", "fix_all_activities.py", "fix_categorizer_cache.py",
        "fix_column_types.py", "fix_dashboard.bat", "fix_database_types.py",
        "fix_duration_data.py", "fix_users_table.py", "fix_working_hours.py",
        "flexible_dashboard_fix.py", "force_fix_and_start.py", "fix_categorizer_cache.bat",
        "fix_categorizer_cache.sh",
        
        # Quick/simple files
        "quick_dashboard_diagnosis.py", "quick_dashboard_test.py", "quick_db_check.py",
        "quick_fix_case_sensitivity.py", "quick_fix_registration.py", "quick_type_check.py",
        "simple_developer_registration.html", "simple_fix.py", "simple_multi_dev_api.py",
        "simple_sync.py", "simple_test.py", "simple_token_creator.py",
        
        # Old/backup/enhanced files
        "activity_categorizer_old.py", "main.py.backup", "activity_analyzer_fixed.py",
        "dashboard_api_enhanced.py", "dashboard_api_fixed.py", "fixed_data_puller.py",
        "fixed_developer_discovery.py", "fixed_dynamic_developer_api.py", "fixed_registration_final.py",
        "fixed_sync_endpoint.py", "fixed_top_window_titles.py",
        
        # Setup/migration files
        "setup_automated_puller.sh", "setup_developers_table.py", "setup_multi_dev.py",
        "setup_multi_dev_clean.py", "setup_postgres.py", "setup_windows_sync.bat",
        "database_migration.py", "migrate_detailed_info.py",
        
        # HTML files
        "developer-setup.html", "developers_list.html", "developer_list.html",
        "register-developer.html",
        
        # Other unnecessary files
        "New Text Document.txt", "complete_dashboard_fix.bat", "comprehensive_fix.sh",
        "dashboard_fix_solution.bat", "db_info.py", "extract_app_data.py",
        "extract_projects.py", "find_data_dates.py", "find_query_source.py",
        "improved_project_extractor.py", "inspect_database.py", "minimal_main.py",
        "open_dashboard_with_data.py", "query_database.py", "realistic_hours_calculator.py",
        "real_data_endpoints.py", "remove-all-tokens.py", "run_all_fixes.py",
        "safe_cleanup_project.py", "sample_data.py", "start_backend_debug.py",
        "start_data_puller.bat", "start_direct.py", "update_categories.py",
        
        # Additional files with patterns
        "categorized_from_json.py", "categorize_all_activities.py", "categorize_sqlalchemy.py",
        "add_compatibility.py", "add_date_endpoints.py", "developer_discovery.py",
        "developer_model_addition.py", "dynamic_activitywatch_client.py", "dynamic_api_endpoints.py",
        "dynamic_developer_api.py", "dynamic_discovery.py", "dynamic_token_manager.py",
        "enhanced_activity_api.py", "multi_developer_api.py", "my_activitywatch_client.py",
        "project_assignment_api.py", "project_extractor.py", "productivity_calculator.py",
        "registration_endpoints.py", "safe_activity_caching.py", "stateless_webhook.py",
        "developers_orm_api.py", "daily_hours_calculator.py"
    ]
    
    for filename in files_to_remove:
        filepath = backend_dir / filename
        if filepath.exists() and filepath.is_file():
            try:
                dest = backend_trash / filename
                shutil.move(str(filepath), str(dest))
                print(f"  Moved: {filename}")
                moved += 1
            except Exception as e:
                print(f"  Error moving {filename}: {e}")
    
    return moved

def cleanup_directories():
    """Clean up debug/test directories"""
    print("\n3. Cleaning up directories...")
    moved = 0
    
    # Directories to remove
    dirs_to_remove = [
        ("__to_delete__", BASE_DIR / "__to_delete__"),
        ("backend/debug", BASE_DIR / "backend" / "debug"),
        ("backend/__pycache__", BASE_DIR / "backend" / "__pycache__"),
        ("backend/logs", BASE_DIR / "backend" / "logs"),
        ("backend/scripts", BASE_DIR / "backend" / "scripts"),
        ("backend/sync_scripts", BASE_DIR / "backend" / "sync_scripts"),
    ]
    
    for name, dirpath in dirs_to_remove:
        if dirpath.exists() and dirpath.is_dir():
            try:
                dest = TRASH_DIR / f"dir_{name.replace('/', '_')}"
                shutil.move(str(dirpath), str(dest))
                print(f"  Moved directory: {name}")
                moved += 1
            except Exception as e:
                print(f"  Error moving {name}: {e}")
    
    return moved

def main():
    """Main cleanup function"""
    print("=" * 60)
    print("TIMESHEET PROJECT CLEANUP")
    print("=" * 60)
    
    # Clean root directory
    root_moved = cleanup_root()
    
    # Clean backend directory
    backend_moved = cleanup_backend()
    
    # Clean directories
    dirs_moved = cleanup_directories()
    
    # Also move the cleanup script itself
    cleanup_summary = BASE_DIR / "cleanup_summary.txt"
    if cleanup_summary.exists():
        shutil.move(str(cleanup_summary), str(TRASH_DIR / "cleanup_summary.txt"))
    
    total_moved = root_moved + backend_moved + dirs_moved
    
    print("\n" + "=" * 60)
    print(f"CLEANUP COMPLETE!")
    print(f"Total files moved: {total_moved}")
    print(f"All removed files are in: {TRASH_DIR}")
    print("\nTo permanently delete, remove the __cleanup_trash__ directory")
    print("=" * 60)

if __name__ == "__main__":
    main()
