#!/usr/bin/env python3
"""
Fix for ActivityCategorizer cache issue
This script clears Python cache and restarts the backend
"""
import os
import shutil
import subprocess
import time

def main():
    print("🔧 Fixing ActivityCategorizer cache issue...")
    
    # 1. Stop the PM2 process
    print("📍 Stopping timesheet-backend...")
    subprocess.run(["pm2", "stop", "timesheet-backend"], capture_output=True)
    time.sleep(2)
    
    # 2. Clear Python cache
    pycache_dir = os.path.join(os.path.dirname(__file__), "__pycache__")
    if os.path.exists(pycache_dir):
        print(f"🗑️  Removing Python cache from {pycache_dir}")
        shutil.rmtree(pycache_dir)
    
    # 3. Also remove specific .pyc files
    pyc_files = [
        "activity_categorizer.cpython-312.pyc",
        "fixed_sync_endpoint.cpython-312.pyc",
        "activity_categorization_api.cpython-312.pyc",
        "enhanced_activity_api.cpython-312.pyc"
    ]
    
    for pyc_file in pyc_files:
        pyc_path = os.path.join(os.path.dirname(__file__), pyc_file)
        if os.path.exists(pyc_path):
            print(f"🗑️  Removing {pyc_file}")
            os.remove(pyc_path)
    
    # 4. Restart the backend
    print("🚀 Restarting timesheet-backend...")
    subprocess.run(["pm2", "restart", "timesheet-backend"], capture_output=True)
    
    # 5. Show logs to confirm it's working
    print("\n📋 Checking logs...")
    time.sleep(3)
    subprocess.run(["pm2", "logs", "timesheet-backend", "--lines", "10"])
    
    print("\n✅ Fix completed! The backend should now be running without the 'non_work_keywords' error.")
    print("\n💡 If the error persists, try:")
    print("   1. pm2 delete timesheet-backend")
    print("   2. pm2 start main.py --name timesheet-backend --interpreter python3")

if __name__ == "__main__":
    main()
