import os
import sys
import pickle

# --- Setup Project Path ---
# This allows the script to be run from anywhere and still find the necessary modules.
current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.dirname(current_dir)
if project_root not in sys.path:
    sys.path.append(project_root)
# --- End Setup ---

from franai.models.staff_model import Staff

# --- Configuration ---
# This should match the directory defined in your server.py
EMBEDDINGS_DIR = "insightface_embeddings"
# --- End Configuration ---

def sync_all_pkl_files():
    """
    Iterates through all .pkl files, fetches the latest user data from the HRIS database,
    and updates the name and department in the .pkl file if they are out of sync.
    """
    print("--- Starting PKL File Synchronization ---")
    
    if not os.path.isdir(EMBEDDINGS_DIR):
        print(f"❌ ERROR: Embeddings directory not found at '{EMBEDDINGS_DIR}'")
        return

    embedding_files = [f for f in os.listdir(EMBEDDINGS_DIR) if f.startswith('insightface_embeddings_') and f.endswith('.pkl')]
    
    if not embedding_files:
        print("No .pkl files found to sync.")
        return

    print(f"Found {len(embedding_files)} .pkl files to check...")
    
    updated_count = 0
    checked_count = 0
    error_count = 0

    for filename in embedding_files:
        checked_count += 1
        try:
            # 1. Extract user_id from filename
            user_id_str = filename.replace('insightface_embeddings_', '').replace('.pkl', '')
            user_id = int(user_id_str)

            # 2. Fetch latest user info from the database
            employee_info = Staff.get_by_pid(user_id)
            if not employee_info:
                print(f"⚠️  Skipping User ID {user_id}: Not found in HRIS database.")
                continue

            # 3. Read the existing PKL file
            file_path = os.path.join(EMBEDDINGS_DIR, filename)
            with open(file_path, 'rb') as f:
                data = pickle.load(f)

            # 4. Compare and update if necessary
            new_name = f"{employee_info.get('first_name', '')} {employee_info.get('last_name', '')}".strip()
            new_department = employee_info.get('team_name', 'N/A')
            
            current_name = data.get('name', '')
            current_department = data.get('department', '')

            if new_name != current_name or new_department != current_department:
                print(f"🔄 UPDATING User ID {user_id}:")
                if new_name != current_name:
                    print(f"   - Name: '{current_name}' -> '{new_name}'")
                if new_department != current_department:
                    print(f"   - Dept: '{current_department}' -> '{new_department}'")
                
                data['name'] = new_name
                data['department'] = new_department
                
                with open(file_path, 'wb') as f:
                    pickle.dump(data, f)
                
                updated_count += 1
            else:
                print(f"✅ OK: User ID {user_id} ('{current_name}') is already up to date.")

        except (ValueError, KeyError, pickle.UnpicklingError) as e:
            print(f"❌ ERROR processing file {filename}: {e}")
            error_count += 1
            continue

    print("\n--- Synchronization Complete ---")
    print(f"Total files checked: {checked_count}")
    print(f"Files updated: {updated_count}")
    print(f"Errors encountered: {error_count}")
    print("---------------------------------")

if __name__ == "__main__":
    sync_all_pkl_files()
