"""
Final cleanup script - moves all debug/test files to trash
"""

import os
import shutil
from pathlib import Path

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

# Ensure trash directories exist
(TRASH_DIR / "root").mkdir(parents=True, exist_ok=True)
(TRASH_DIR / "backend").mkdir(parents=True, exist_ok=True)
(TRASH_DIR / "dirs").mkdir(parents=True, exist_ok=True)

# Files already moved
already_moved = {
    "CHECK-AUTOMATION-STATUS.bat",
    "CHECK-STATUS.bat", 
    "DEBUG-SYNC.bat"
}

# Root files to move
root_files_to_move = [
    # BAT files
    "CLICK-TO-FIX-MAIL.bat", "COMPLETE-AUTOMATION-SOLUTION.bat", 
    "COMPLETE-FIX-FIRST-ECONOMY-MAIL.bat", "CONFIGURE-FIRST.bat",
    "CREATE-DEVELOPER-PACKAGE.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",
    "find_error.bat",
    
    # Python 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",
    "ONE_CLICK_MAIL_FIX.py", "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", "frontend_project_grouping_example.js",
    "activity_categorization_api_fixed.py", "activity_categorization_api_modified.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",
    
    # Documentation files
    "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",
    
    # Scripts
    "fix_categories.sh", "sync.ps1", "sync.sh",
    "hidden-launcher.vbs", "quick_fix_commands.sh",
    
    # Cleanup files
    "cleanup_project.py", "cleanup_simple.py", "cleanup_summary.txt",
    "CLEANUP_NOW.bat", "CLEANUP_MANIFEST.txt"
]

# Backend files to move
backend_files_to_move = [
    # Test/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_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",
    
    # Other unnecessary 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", "complete_dashboard_fix.bat",
    "comprehensive_fix.sh", "dashboard_fix_solution.bat",
    "db_info.py", "developer-setup.html", "developers_list.html",
    "developer_list.html", "simple_developer_registration.html",
    "register-developer.html", "New Text Document.txt",
    
    # Simple/quick 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_fix.py", "simple_multi_dev_api.py",
    "simple_sync.py", "simple_test.py", "simple_token_creator.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",
    
    # Extra files
    "add_compatibility.py", "add_date_endpoints.py",
    "categorized_from_json.py", "categorize_all_activities.py",
    "categorize_sqlalchemy.py", "developer_discovery.py",
    "developer_model_addition.py", "developers_orm_api.py",
    "dynamic_activitywatch_client.py", "dynamic_api_endpoints.py",
    "dynamic_developer_api.py", "dynamic_discovery.py",
    "dynamic_token_manager.py", "enhanced_activity_api.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", "multi_developer_api.py",
    "my_activitywatch_client.py", "open_dashboard_with_data.py",
    "project_assignment_api.py", "project_extractor.py",
    "query_database.py", "realistic_hours_calculator.py",
    "real_data_endpoints.py", "registration_endpoints.py",
    "remove-all-tokens.py", "run_all_fixes.py",
    "safe_activity_caching.py", "safe_cleanup_project.py",
    "sample_data.py", "start_backend_debug.py",
    "start_data_puller.bat", "start_direct.py",
    "stateless_webhook.py", "update_categories.py"
]

# Move root files
print("Moving root files...")
moved_count = 0
for filename in root_files_to_move:
    if filename in already_moved:
        continue
    
    src = BASE_DIR / filename
    if src.exists():
        try:
            dest = TRASH_DIR / "root" / filename
            shutil.move(str(src), str(dest))
            print(f"  Moved: {filename}")
            moved_count += 1
        except Exception as e:
            print(f"  Error moving {filename}: {e}")

# Move backend files
print("\nMoving backend files...")
backend_dir = BASE_DIR / "backend"
for filename in backend_files_to_move:
    src = backend_dir / filename
    if src.exists():
        try:
            dest = TRASH_DIR / "backend" / filename
            shutil.move(str(src), str(dest))
            print(f"  Moved: backend/{filename}")
            moved_count += 1
        except Exception as e:
            print(f"  Error moving backend/{filename}: {e}")

# Move directories
print("\nMoving directories...")
dirs_to_move = [
    (BASE_DIR / "__to_delete__", TRASH_DIR / "dirs" / "__to_delete__"),
    (backend_dir / "debug", TRASH_DIR / "dirs" / "backend_debug"),
    (backend_dir / "logs", TRASH_DIR / "dirs" / "backend_logs"),
    (backend_dir / "scripts", TRASH_DIR / "dirs" / "backend_scripts"),
    (backend_dir / "sync_scripts", TRASH_DIR / "dirs" / "backend_sync_scripts"),
    (backend_dir / "__pycache__", TRASH_DIR / "dirs" / "backend_pycache"),
]

for src, dest in dirs_to_move:
    if src.exists():
        try:
            shutil.move(str(src), str(dest))
            print(f"  Moved directory: {src.name}")
            moved_count += 1
        except Exception as e:
            print(f"  Error moving {src.name}: {e}")

# Move frontend fix script
frontend_dir = BASE_DIR / "frontend"
fix_script = frontend_dir / "fix-api-urls.ps1"
if fix_script.exists():
    try:
        dest = TRASH_DIR / "root" / "fix-api-urls.ps1"
        shutil.move(str(fix_script), str(dest))
        print(f"  Moved: frontend/fix-api-urls.ps1")
        moved_count += 1
    except Exception as e:
        print(f"  Error moving frontend script: {e}")

print(f"\n{'='*60}")
print(f"CLEANUP COMPLETE!")
print(f"Total items moved: {moved_count}")
print(f"Trash location: {TRASH_DIR}")
print(f"{'='*60}")

# List remaining files in root
print("\nRemaining files in root:")
for item in sorted(BASE_DIR.iterdir()):
    if item.is_file() and item.name != "final_cleanup.py":
        print(f"  • {item.name}")

print("\nRemaining files in backend:")
essential_backend = {
    "main.py", "models.py", "schemas.py", "database.py",
    "config.py", "auth.py", "crud.py", "__init__.py",
    "activity_categorizer.py", "activity_categorization_api.py",
    "activitywatch_sync.py", "activitywatch_webhook.py",
    "dashboard_api.py", "productivity_api.py",
    "all_developers_simple.py", "daily_hours_calculator.py",
    "productivity_calculator.py", "timesheet.db",
    ".env", ".env.local", ".env.production"
}

for item in sorted(backend_dir.iterdir()):
    if item.is_file() and item.name in essential_backend:
        print(f"  • {item.name}")

print(f"\nTo permanently delete the trash, run:")
print(f"  rmdir /s /q \"{TRASH_DIR}\"")
